Like Us On Facebook

Total Pageviews

231. Using printStackTrace( ) of Throwable Class

Pre-requisites -

Till now, the basic details of the exception got displayed on using the getMessage( ) and toString( ) methods. But in order to get the complete details of the exception we have to use the printStackTrace( ) method of Throwable Class.

printStackTrace( ) method gets the complete details of the occurred exception like exception name, exception cause, Class Name, Method Name and the line where the exception has occurred in the program code.

Syntax -

exception.printStackTrace( );  //These statement prints the exception details without the need of any print statements.

Lets implement this on Eclipse IDE -

1. Launch Eclipse IDE, create a statement in the catch( ) block of '' Class of the existing Java Project 'Project 46' as shown below -

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

By observing the above shown output, the following details are displayed -
  • Exception Name - java.lang.ArithmeticException
  • Exception Cause - / by zero
  • Exception Occurred at PrintExceptions Class, main( ) method and at line number 7  

Using the above output, lets find out the statement in our program code which has caused this exception.

3. As our output clearly said that the exception has occurred in step 7. Lets view the step 7 in our program.

4. To view the Line number, we have to right click in the bar to the left of the code as shown below and select 'Show Line Numbers' option as shown below -

5. Observe that the line numbers got displayed in the pane and view the line number 7 which has caused the exception our program code as shown below -

Hence using the output we are able to identify the statement that has thrown the exception in our program code.

Please comment below to feedback or ask questions.

Using throw keyword in exception handling will be explained in the next post

No comments:

Blog Index