Java Programming Handbook

    Try and Catch Block in Java

    Introduction#

    In the previous blog, we introduced exception handling in Java and briefly discussed the try-catch mechanism. Now, let's take a deeper dive into how the try and catch blocks work, along with best practices and real-world examples.

    In this blog, we will cover:

    • What is a try block?
    • What is a catch block?
    • How try-catch works internally
    • Handling multiple exceptions
    • Best practices for using try-catch

    What is a try Block?#

    A try block contains the risky code that might generate an exception. It allows Java to test a section of code for potential exceptions without stopping the execution of the program.

    Syntax:#

    try { // Code that may cause an exception }

    Example:

    public class TryExample { public static void main(String[] args) { try { int number = 10 / 0; // Risky code (Division by zero) System.out.println(number); } } }

    Output:

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

    👉 Notice that the program crashes because there's no catch block to handle the exception.

    What is a catch Block?#

    A catch block is used to handle exceptions thrown from the try block. It prevents the program from crashing by executing alternative code when an exception occurs.

    Syntax:#

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

    Example:#

    public class TryCatchExample { public static void main(String[] args) { try { int number = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero!"); } System.out.println("Program continues..."); } }

    Output:

    Cannot divide by zero! Program continues...

    👉 Now, the exception is handled, and the program doesn't crash.

    How try-catch Works Internally#

    1. The program starts executing the try block.
    2. If no exception occurs, the catch block is skipped.
    3. If an exception occurs:
      • Execution immediately jumps to the catch block.
      • The rest of the try block is skipped.
    4. After handling the exception, the program continues executing normally.

    Here’s an example where no exception occurs:

    public class NoExceptionExample { public static void main(String[] args) { try { int num = 10 / 2; System.out.println("Result: " + num); } catch (ArithmeticException e) { System.out.println("An error occurred."); } System.out.println("Program finished."); } }

    Output:

    Result: 5 Program finished.

    👉 The catch block is skipped because no error occurred.

    Handling Multiple Exceptions#

    Sometimes, multiple exceptions may occur in a single try block. Java allows handling them using multiple catch blocks.

    Example:#

    public class MultipleCatchExample { public static void main(String[] args) { try { int[] numbers = {1, 2, 3}; System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException } catch (ArithmeticException e) { System.out.println("Arithmetic error occurred."); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array index is out of bounds."); } } }

    Output:

    Array index is out of bounds.

    👉 Java checks each catch block sequentially to find a match for the exception type.

    Catching Multiple Exceptions in One catch Block (Java 7+)#

    Instead of writing multiple catch blocks, Java allows handling multiple exceptions in a single catch block using the | (pipe) symbol.

    Example:#

    public class MultiCatchExample { public static void main(String[] args) { try { int num = Integer.parseInt("abc"); // NumberFormatException } catch (ArithmeticException | NumberFormatException e) { System.out.println("An error occurred: " + e.getMessage()); } } }

    Output:

    An error occurred: For input string: "abc"

    👉 This approach makes the code cleaner and reduces redundancy.

    Best Practices for Using try-catch#

    • Always catch specific exceptions instead of using a generic Exception class (unless necessary).
    • Avoid empty catch blocks, as they make debugging difficult.
    • Use meaningful exception messages to help identify the problem quickly.
    • Do not use try-catch to suppress errors that should be fixed in the code instead.
    • Keep try blocks short – only include the code that might throw an exception.

    Conclusion#

    In this blog, we covered:

    • The purpose of try and catch blocks.
    • How exceptions are caught and handled.
    • The internal working of the try-catch mechanism.
    • Handling multiple exceptions using separate and combined catch blocks.

    In the next blog, we will explore Multiple and Nested Try-Catch Blocks with practical examples.

    Last updated on Apr 09, 2025