Google+

221. Catching exceptions using Exception Class







Pre-requisite -


Exception Class is the child class of Throwable Class but it 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 Exception Class is the parent class of all exception classes, the object of its sub-class can be assigned to the object of the Exception Class. Once the object of sub-class is assigned to the object of Exception class using the try{ } block, the received object gets upcasted to the Exception Class object and the Exception 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 Exception Parent Class object.

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

}

Lets implement this on Eclipse IDE -

1. Launch Eclipse IDE, in the existing Java Project 'Project 46', create a Class 'ExceptionDemo' with main( ) method as shown below -



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


3. 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 -


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



5. Now lets print the occurred arithmetic exception using the Exception Class object as shown below -



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


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






Please comment below to feedback or ask questions.

Catching arithmetic exceptions using ArithmeticException Class  will be explained in the next post











No comments: