Java Try Catch Block

Last Updated : 25 Nov, 2026

A try-catch block in Java is used to handle exceptions that occur during program execution. It allows the program to respond to errors without terminating unexpectedly when the exception is handled.

  • The try block contains code that may throw an exception.
  • The catch block handles an exception when its type matches the specified exception class.

Example: Program to demonstrate the try-catch block in Java.

Java
class Geeks{
    public static void main(String[] args){
        try{
            
            // Division by zero throws an exception
            int result = 10 / 0;
            System.out.println(result);
        }catch (ArithmeticException e){
            System.out.println("Exception caught: " + e);
        }

        // Executes after the exception is handled
        System.out.println("Program continues...");
    }
}

Output
Exception caught: java.lang.ArithmeticException: / by zero
Program continues...

Explanation:

  • The expression 10 / 0 throws an ArithmeticException.
  • The matching catch block handles the exception and prints its details.
  • After the catch block completes, execution continues with the next statement.

Syntax of Try-Catch Block

try{
// Code that may throw an exception
}catch (ExceptionType e){
// Code to handle the exception
}

  • try contains statements that may throw an exception.
  • catch handles exceptions matching the specified type. The parameter e refers to the caught exception object.

A try block must be followed by at least one catch or finally block, unless it uses the try-with-resources form.

Internal Working of Try-Catch Block

When an exception occurs inside a try block, Java searches for a suitable exception handler.

java_try_catc
Working of Try-Catch Block

The process follows these steps:

  • Java executes statements inside the try block.
  • If an exception occurs, the remaining statements in that try block are skipped.
  • Java checks whether the associated catch block matches the exception type.
  • If a matching handler is found, its statements execute.
  • After the exception is handled, execution continues after the try-catch statement.
  • If no matching handler is found, the exception propagates to the calling method, where another handler may catch it.

Related Articles:

Comment