220. Catching Exceptions using Throwable Class

Pre-requisite -

Throwable Class is the parent class of all the Exception Classes in Java. Hence it can handle any kind of exception internally using the upcasting feature (i.e. Assigning sub-class object to the Parent Class object).

As Throwable Class is the parent class of all exception classes, the object of its sub-class can be assigned to the object of the Throwable Class. Once the object of sub-class is assigned to the object of Throwable class using the try{ } block, the received object gets upcasted to the Throwable Class object and the Throwable Class object can be used to handle the exception.

Example -

Lets say we got an Arithmetic exception in the code as shown below. When we handle this exception using the try{ } catch{ } blocks, try{ } will throw the exception (i.e. object) of the sub-class 'ArithmeticException' and catch block catches the exception into the Throwable Parent Class object.

class ClassOne
          int i = 5/0;  //Throws Arithmetic Exception
     catch(Throwable object1)
          System.out.println("Exception Details - "+object1);


Lets implement this on Eclipse IDE -

1. Launch Eclipse IDE, create a Java Project 'Project 46' as shown below -

2. Create a Class 'ThrowableDemo' with main( ) method as shown below -

3. Inside the main( ) method, intentionally write the statement int i = 5/0; which throws Arithmetic Exception as shown below -

4. Now handle the exception using the try{ } catch{ } blocks by first placing the statement which throws the arithmetic exception in try{ } block as shown below -

5. Now write the catch{ } block which catches the Arithmetic exception thrown by the try{} block into the Throwable Class object as shown below -

6. Now lets print the occurred arithmetic exception using the Throwable Class object as shown below -

7. Run the Java Class file '' and observe that the arithmetic exception details are displayed in the output using the object of Throwable Class in the above code as shown below -

Hence we can catch the exceptions using the Throwable Class, as all the classes that throw exceptions are the sub-classes of the Throwable Class.

Please comment below to feedback or ask questions.

Catching exceptions using Exception Class will be explained in the next post.

No comments: