Exception Handling in Java

Exception is an event occurred while program execution. This event causes abnormal termination of the program. When the program terminates abnormally it can disturb the normal flow of the system. Hence, to avoid this problem every programmer should handle the Exception.

Exception handling is the mechanism by which we overcome the condition of abnormal termination and helps the program to exit smoothly.

Before going further there are two terms which we should understand. These terms are Errors and Exceptions. There are lots of differences between these two terms. Let’s discuss these terms one by one.

Errors

They are incidence which causes serious termination of the program. They are the subclass of java.lang.Throwable class. They are the conditions which can be handled by any handling technique. They below to unchecked type and mostly occurs at runtime. When the error condition occurs it surely result into termination of program. OutOfMemory error or System error is an example of error.

Output:

Exception in thread “main” java.lang.StackOverflowError

Exception

Exception are the condition which can be handled. Exception can be both runtime as well as compile time. These conditions can be handled easily by using Exception handling mechanism.

Exception class is mainly divided into two categories:

1. Checked Exception are the exception with occurs at compile time. Exceptions like IOException is an example of checked exception.

2. Unchecked Exception are the exception which are known to the compiler at runtime. Exceptions like ArrayIndexOutOfBound is an example of  Unchecked Exception.

Output:

Java.lang.ArithmeticException: / by zero

Exception Hierarchy

All exceptions are sub-class of Exception class. Exception class is the sub-class of Throwable class and Throwable class is the sub-class of Object class. Below is the diagram for Exception Hierarchy.



Handling Exception using try-catch block

Java provides a way using which we can handle the exception event in our program. This mechanism of handing the exception is known as Exception Handling. Try and catch keywords are used in order to handle the exception. The piece of code which can cause exception can be surrounded with try and catch block. The code which is placed in try and catch block is known as protected code. The syntax is given below:

try{

   // Code which can throw exception

}catch(Exception ex){

   // Catch block

}

The type of exception which is thrown from try block should be handled by catch block. If the type of exception is listed in the catch block, the exception will be passed to the catch block as an argument. Below is the code snippet.

Output

Exception Caught : java.lang.ArrayIndexOutOfBoundException: 4

Out of Block

 

Multiple catch block

A single try can be grouped with multiple catch blocks. The multiple catch blocks can have different exception types. Syntax goes like this:

try{

   //code which can throw exception

}catch(ExceptionType1 ex){

   // Catch block

} catch(ExceptionType2 ex){

   // Catch block

} catch(ExceptionType3 ex){

   // Catch block

} catch(ExceptionType4 ex){

   // Catch block

}


After a single try we can have any number of catch block. If the exception is thrown from the protected block then the exception will be thrown to the first catch block. If the data type of the exception thrown matches the parameter type of first catch then it will be handled by that catch block. If not, it will be passed to next catch block and so on.

Example:

Handling Multiple Exceptions with single catch block

Since java7 there is a change in the above syntax. We can throw multiple exception into one catch block. Syntax goes like this:

try{

   //code which can throw exception

}catch(IOException | FileNotFoundException fnfe){

   // Catch block

}

 

The “|” symbol is used to separate the different types of exceptions.

 

Throws and throw keyword

Both these keywords are used to handle exception but there is a small difference between these two.

The throws keyword is used at the end of the method’s signature. It is method level declaration that a method might throw this type of exception.

The throw keyword is used inside the method. We can throw a newly created instance or can also throw an exception that you just caught.

The throws keyword is used to postpone the handling the checked exception whereas the throw keyword is used to invoke an exception.

A method can also throws multiple exception types separated by comma. Example below:

The finally block

The finally block is the block which always executes irrespective of the occurrence of the exception. In finally block we can perform clean-up operations like closing the connection and making the object garbage collected.

Finally block appears at the end of the catch block. Example for finally block is given below:

Output:

Exception Caught in catch : java.lang.ArrayIndexOutOfBoundException: 4

Inside finally block.

 

Important notes:

·       Whenever try/catch is present it is not compulsory to implement finally block

·       Try, catch, finally block should be back to back. No code should be written in between them.

·       We can not write catch without try block.

·       We can have a try without a catch block but finally should be present.

User defined Exceptions

Java provides a way to create user defined exception. The custom exception class should extends Exception class.

Output:

Caught in catch

Custom Exception thrown

Conclusion

With this discussion we come to a conclusion that using java try catch mechanism we can handle the exception easily and also we can create the user defined exception.

Post a Comment

0 Comments