Google+

230. Using toString( ) of Throwable Class









Pre-requisite -



toString( ) when used with exception (i.e. object) prints the System Defined Message with basic details.  

Syntax -  exception.toString( )

But, the following two statements gives the same out when used in catch block and an exception is handled -
  1. System.out.println(exception);
  2. System.out.println(exception.toString( ));
Output for the above two statement is same -

java.language.ArithmeticException: /by zero


Lets implement this on Eclipse IDE -

1. Launch Eclipse IDE, write the below statement in the catch block of 'PrintExceptions.java' Class of  the existing project as shown below -

2. Save and Run the Java Class 'PrintExceptions.java' and observe that the above thrown arithmetic exception is handled by printing the following in the output -



Hence printing the exception directly or by using the exception.toString( ) will give the same output as shown above . Basic details of the exception i.e. exception name and its cause are displayed.






Please comment below to feedback or ask questions.

Using printStackTrace( ) of Throwable Class will be explained in the next post.







No comments: