Java – try block

checkout the sourcecode here

Java try block is used to enclose the code that might throw an exception. It must be used within the method.

Java try block must be followed by either catch or finally block.

Syntax of java try-catch

try{
//code that may throw exception  
        }catch(Exception_class_Name ref){}

Syntax of try-finally block

try{
//code that may throw exception  
        }finally{}

Java catch block

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

You can use multiple catch block with a single try.


Problem without exception handling

Let’s try to understand the problem if we don’t use try-catch block.

}
public class Testtrycatch1{
    public static void main(String args[]){
        int data=50/0;//may throw exception  
        System.out.println("rest of the code...");
    }
}

Test it Now

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero

As displayed in the above example, rest of the code is not executed (in such case, rest of the code… statement is not printed).

There can be 100 lines of code after exception. So all the code after exception will not be executed.


Solution by exception handling

Let’s see the solution of above problem by java try-catch block.

package exceptionhandling;

public class Testtrycatch2 {
    public static void main(String args[]) {
        try {
            int data = 50 / 0;
        } catch (ArithmeticException e) {
            System.out.println(e);
        }
        System.out.println("rest of the code...");
    }
}

Test it Now

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

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


Internal working of java try-catch block

internal working of 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.

Leave a Reply

Your email address will not be published. Required fields are marked *