Senin, 25 April 2016

3 different ways to print exception message in java

  • In Java there are three ways to find the details of the exception .
  • They are 
  1. Using an object of java.lang.Exception
  2. Using public void printStackTrace() method
  3. Using public String getMessage() method.

1.Using an object of java.lang.Exception

  •  An object of Exception class prints the name of the exception and nature of the exception.



Write a Java program get detailed message details using exception class object



  1. package exceptions;
  2. public class ExceptionDetails {
  3.  
  4. /**
  5.  * @www.instanceofjava.com
  6.  **/
  7.  public static void main(String[] args) {
  8.  
  9. try {
  10.  
  11. int x=1/0;
  12.             
  13. } catch (Exception e) {
  14.             System.out.println(e);
  15. }
  16.  
  17. }
  18.  
  19. }

 Output:


  1. java.lang.ArithmeticException: / by zero


 2.Using  public void printStackTrace() method


  • This is the method which is defined in java.lang.Throwable class and it is inherited into java.lang.Error class and java.lang.Exception class
  • This method will display the name of the exception and nature of the message and line number where exception has occurred.

Write a simple java example program to print exception message to console using printStacktrace() method



  1. package exceptions;
  2. public class ExceptionDetails {
  3.  
  4.     /**
  5.      * @www.instanceofjava.com
  6.      */
  7. public static void main(String[] args) {

  8.  
  9.  try {
  10.           int a[]= new int[1];
  11.             a[1]=12
  12.             
  13. } catch (Exception e) {
  14.    e.printStackTrace();
  15.            
  16.  }
  17. }
  18.  
  19. }

 Output:


  1. java.lang.ArrayIndexOutOfBoundsException: 1
        at exceptions.ExceptionDetails.main(ExceptionDetails.java:13)

  3.Using public String getMessage() method

  •  This is also a method which is defined in java.lang.Throwable class and it is inherited in to both java.lanf.Error and java.lang.Exception classes.
  • This method will display the only exception message


Write a Java program print exception message using getMessage() method.


  1. package exceptions;
  2. public class ExceptionDetails {
  3.  
  4.     /**
  5.      * @www.instanceofjava.com
  6.      */
  7.     public static void main(String[] args) {

  8.  
  9.         try {
  10.             int x=1/0;
  11.             
  12.         } catch (Exception e) {
  13.             System.out.println(e.getMessage());
  14.         }
  15.     }
  16.  
  17. }

 Output:


  1.  / by zero

print exception message

Bagikan

Jangan lewatkan

3 different ways to print exception message in java
4/ 5
Oleh

Subscribe via email

Suka dengan artikel di atas? Tambahkan email Anda untuk berlangganan.