try & catch block and Handling Exceptions

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:

try
{
   //Protected code
}catch(ExceptionName e1)
{
   //Catch block
}


Exception Handling in Java

It is a powerful feature provided in Java. It is a mechanism to handle run-time errors, so that the normal flow of the program is maintained.

Exception handling consists of the following five keywords:

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

try block
Enclose the code that might throw an exception in try block. It must be used within the method and must be followed by either catch or finally block.
Syntax of try with catch block

try{
...
}catch(Exception_class_Name reference){}


Syntax of try with finally block

try{
...
}finally{}

catch block
Catch block is used to handle the Exception. It must be used after the try block.

Code without exception handling:

class App{
  public static void main(String args[]){
      int index = 10/0;
  
      System.out.println("another code here");
    }
 }
try & catch block and Handling Exceptions

As displayed in the above example, rest of the code is not executed i.e. another code here statement is not printed. Let’s see what happens behind the scene:

try & catch block

The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks:

  • Prints out exception description.
  • Prints the stack trace (Hierarchy of methods where the exception occurred).
  • Causes the program to terminate.

But if exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the code is executed. 
Code with exception handling:

class App{
  public static void main(String args[]){
      try{
          int index = 10/0;
      }catch(ArithmeticException e){
            System.out.println(e);
      }
      System.out.println("another code here");
    }
 }
Handling Exceptions

Now, as displayed in the above example, rest of the code is executed i.e. another code here. statement is printed.

<<Previous <<   || Index ||   >>Next >>

Previous
Next