Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Master Java Exception Handling: Try‑Catch, Finally, and Class Hierarchy Explained

What is Exception in Java?

Exception in Java is an event that interrupts the execution of program instructions, disrupting the normal flow of control. It is an object that encapsulates error information that arises within a method and is passed to the runtime system. In Java, exceptions primarily signal different error conditions that cannot be handled by standard control flow.

In this tutorial you’ll learn:

Errors in Java fall into two broad categories:

  1. Compile‑time errors
  2. Runtime errors

Compile‑time errors can be further divided into:

Syntax error example:

Declaring int a; is correct, but writing in a; will cause the compiler to report an error.

For instance, declaring int a; once and then attempting to redeclare int a; later in the same scope will trigger a compiler error, which is highlighted during the build.

Runtime error example

Runtime errors manifest as exceptions, events that interrupt normal execution flow. Typical examples include ArithmeticException, NullPointerException, and division by zero.

These exceptions arise from conditions beyond the developer’s direct control.

Master Java Exception Handling: Try‑Catch, Finally, and Class Hierarchy Explained

Why do we need Exception Handling?

Consider a program that accesses a remote server. During development, the server is reachable, and the code runs smoothly. In production, the server may be down, causing an exception when the program attempts to connect.

Master Java Exception Handling: Try‑Catch, Finally, and Class Hierarchy Explained

Relying solely on the code’s natural flow is insufficient. Robust programs anticipate exceptional conditions and recover gracefully.

How to Handle Exceptions

Exception handling is the practice of anticipating exceptional conditions and providing fallback logic. A common strategy is to attempt a primary operation and, upon failure, redirect to a backup.

Master Java Exception Handling: Try‑Catch, Finally, and Class Hierarchy Explained

Using traditional if‑else constructs to handle multiple exception types quickly becomes unwieldy:

class Connect {
    if (serverIsUp()) {
        // connect to primary server
    } else {
        // connect to backup server
    }
}

The Try‑Catch Block

Java provides built‑in mechanisms for exception handling. Code that may throw an exception is placed inside a try block, and corresponding recovery code is placed inside one or more catch blocks.

Master Java Exception Handling: Try‑Catch, Finally, and Class Hierarchy Explained

For example, the try block may attempt to connect to the primary server, while the catch block handles the fallback logic.

When the server is up, the catch block is skipped; when the server is down, an exception is thrown, and the catch block executes.

Master Java Exception Handling: Try‑Catch, Finally, and Class Hierarchy Explained

The syntax for a try‑catch pair is:

try {
    // statements that might throw
} catch (ExceptionType name) {
    // recovery statements
}

Practical Example

Step 1: Copy the following code into your IDE.

class JavaException {
    public static void main(String args[]) {
        int d = 0;
        int n = 20;
        int fraction = n / d;  // will throw ArithmeticException
        System.out.println("End Of Main");
    }
}

Step 2: Compile and run. The program throws an ArithmeticException and terminates at line 5.

Step 3: Modify the code to use try‑catch:

class JavaException {
    public static void main(String args[]) {
        int d = 0;
        int n = 20;
        try {
            int fraction = n / d;
            System.out.println("This line will not be executed");
        } catch (ArithmeticException e) {
            System.out.println("Caught exception: " + e);
        }
        System.out.println("End Of Main");
    }
}

Step 4: Compile and run again. The output shows that the exception is handled gracefully, and the program continues to the final print statement.

Master Java Exception Handling: Try‑Catch, Finally, and Class Hierarchy Explained

The caught ArithmeticException object e contains detailed information that can be used for logging or recovery.

Exception Class Hierarchy

Java’s exception hierarchy stems from the Throwable class, which has two direct subclasses: Error and Exception. Error represents unrecoverable conditions (e.g., OutOfMemoryError), while Exception covers conditions that can be handled programmatically.

Master Java Exception Handling: Try‑Catch, Finally, and Class Hierarchy Explained

Nested Try‑Catch Example

Copy the following code:

class JavaException {
    public static void main(String args[]) {
        try {
            int d = 1;
            int n = 20;
            int fraction = n / d;
            int g[] = {1};
            g[20] = 100;  // ArrayIndexOutOfBoundsException
        } catch (ArithmeticException e) {
            System.out.println("Caught ArithmeticException: " + e);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Caught ArrayIndexOutOfBoundsException: " + e);
        }
        System.out.println("End Of Main");
    }
}

When d is 1, the code throws ArrayIndexOutOfBoundsException. Changing d to 0 triggers ArithmeticException. Un-commenting a broad catch (Exception e) would cause a compilation error because it would shadow more specific handlers.

The Finally Block

The finally block executes regardless of whether an exception occurs, making it ideal for cleanup tasks.

try {
    // risky operations
} catch (ExceptionType e) {
    // error handling
} finally {
    // cleanup actions
}

Example:

class JavaException {
    public static void main(String args[]) {
        try {
            int d = 0;
            int n = 20;
            int fraction = n / d;
        } catch (ArithmeticException e) {
            System.out.println("Caught exception: " + e);
        } finally {
            System.out.println("Inside the finally block");
        }
    }
}

Running this program outputs the message from the finally block even though an exception is thrown. Changing d to 1 eliminates the exception; the finally block still runs.

Summary:

Java

  1. Java Exceptions: Types, Hierarchy & Handling
  2. Mastering Java Exception Handling: Try, Catch, Finally, Throw & Throws Explained
  3. Mastering Java Exception Handling: Try, Catch, Finally, and Resources
  4. Mastering Multi‑Exception Handling in Java
  5. Master C++ Exception Handling: Practical Try, Catch, Throw Examples
  6. Understanding Java's throws Keyword: Examples & Best Practices
  7. Master Python Exception Handling: Using try, except, finally, and raise Effectively
  8. Mastering Java Exceptions: Handling Unexpected Errors Gracefully
  9. Mastering C++ Exception Handling: A Comprehensive Guide
  10. Mastering C# Exception Handling: Strategies & Best Practices