Exception Handling In Java

Exception is a condition. When exception occurs it changes the flow of the program;  due to exception the result of the program gets unaccepted to handle such situation and manage the flow of control. Java provides a String mechanism which is known as exception handling.

Exception handling provides the mechanism to handle exception; without proper exception handling if any exception occurs with the program then JVM determines  the program and displays the error message.

Throwable is the super class of all exceptions.
Checked exception – those exceptions which are necessary to handle before completion are known as checked exceptions. It is just like a syntax error.

E.g. – IOException.

Unchecked exception

In this type of exception it depends onthe programmer whether he wants to handle the exception or not.

E.g. – ArrayIndexOutOfBoundException, NumberFormatException, AirthmaticException, etc.

Java provide five keyword for exception handling.

  1. Try
  2. Catch
  3. Finally
  4. Throw
  5. Throws

Try block:

In try block we write all those statement which can generate any exception. We can handle only those exceptions which occur within try block. If any exception occurs within try block the JRE search the reason of exception then it creates the impliit object of the related class and stores status of the program in the object throws its stand for handling.


  1. try   
  2. {  
  3. //Do work  
  4. }  
Catch block – Exception throw by try block is passed to the catch statement.

  1. catch (Exception Class Name object )  
  2. {  
  3. // Exception handles   
  4. }
Code written within catch statement is also known as exception handler.

Note – we can use single or more catch with a single try block. Each statement is specified for spared exception.

  1. try  
  2. {  
  3. }   
  4. catch(------)  
  5. {  
  6. }  
  7. catch(------)  
  8. {  
  9. }  
Finally – sometime we need to execute any specific statements which are necessary to execute no matter whether the exception occurs or not. Those statemenst must be written within finally block. Finally block gets executed every time no matter if exception occurs or not.

There are two conditions in which finally block is not executed, 
  • System.exit(0);
  • Error

Throw – throw keyword is used to throw user define exception. We can also use this keyword for re-throwing any exception

Throws – when any method is capable of throwing any exception but it doesn’t want to handle it then we use throw keyword after the function prototype. Now it is the responsibility of calling part to property to handle the exception.

Java default handler java itself handles the exception with the help of java default exception handler.

Default exception handler terminates the program and displays the exception message to warning.

Read more articles on Java:

Up Next
    Ebook Download
    View all
    View all