try-catch block

The try-catch block in Java is used to handle exceptions at runtime. It allows developers to write code that might throw an exception (try block), and then catch and handle specific types of exceptions (catch block), preventing abrupt termination of the program.

Basic Syntax

try {
    // Code that might throw an exception
} catch (ExceptionType1 e1) {
    // Handling code for ExceptionType1
} catch (ExceptionType2 e2) {
    // Handling code for ExceptionType2
}
// Optional finally block
finally {
    // Cleanup code that will always execute
}Code language: JavaScript (javascript)

From above,

  • try block: Contains the code that may potentially throw an exception.
  • catch block(s): Catches and handles specific exceptions thrown from the try block.
  • finally block (optional): Contains code that always runs after try and catch, regardless of whether an exception occurred (e.g., closing a file or releasing a resource).

Program

A Java program demonstrating a try-catch block to handle exceptions. This example handles an ArithmeticException when attempting to divide by zero.

public class TryCatchExample {
    public static void main(String[] args) {
        int number1 = 10;
        int number2 = 0;
        int result;

        try {
            // Risky code: division by zero
            result = number1 / number2;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            // Exception handling
            System.out.println("Exception caught: Division by zero is not allowed.");
        }

        System.out.println("Program continues after try-catch block.");
    }
}
/*
Exception caught: Division by zero is not allowed.
Program continues after try-catch block.
*/

Using try-catch blocks in Java helps detect and manage errors at runtime, improving program stability and user experience. It separates error-handling logic from regular logic and ensures the application can recover or report issues cleanly.

Scroll to Top