Implementing Exception Handling in Java Applications

The Nature of Exceptions

An exception represents an abnormal condition that disrupts the normal flow of a program. When an error occurs, Java creates an exception object and hands it off to the Java Virtual Machine (JVM). The JVM then halts program execution and prints the exception details for debugging.

Exception Hierarchy

Every exception class ultimately inherits from the Throwable superclass.

  • Error: Denotes system-level failures (critical problems). Develoeprs rarely handle these directly; they are typically used internally by Oracle/Sun engineers.
  • Expection: Represents conditions that an application might want to catch.
    • RuntimeException (unchecked): The compiler does not enforce handling at compile time; exceptions surface during runtime (e.g., ArrayIndexOutOfBoundsException).
    • Checked excepsions (non-RuntimeException): The compiler forces you to handle or declare them at compile time.

Handling Mechanisms

Approach 1: try-catch-finally Block

Select the suspicious code, then wrap it with a try-catch structure. IntelliJ IDEA shortcut: Ctrl+Alt+T.

try {
    // Code that may throw exceptions
} catch (IOException e) {
    // Handle IOException
} catch (SQLException e) {
    // Handle SQLException
} finally {
    // Always executed, regardless of exception
}

Approach 2: Declaring with throws

Add the throws clause to a method signature to delegate exception handling to the caller.

public static void processData() throws IOException, SQLException {
    // method body that may produce IO or SQL exceptions
}

Defining Custom Exceptions

Unchecked Custom Exception

An unchecked exception does not trigger compile-time errors. The compiler does not require explicit handling.

Steps:

  1. Create a class that extends RuntimeException.
  2. Provide constructors.
  3. Use throw new YourException(message) to raise it.

Custom Exception Class:

public class IllegalNumberException extends RuntimeException {
    public IllegalNumberException() {
    }

    public IllegalNumberException(String message) {
        super(message);
    }
}

Using the Custom Exception:

public class Validator {
    public static void main(String[] args) {
        try {
            validateScore(223);
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

    public static void validateScore(int score) {
        if (score >= 0 && score <= 150) {
            System.out.println("Valid score: " + score);
        } else {
            throw new IllegalNumberException("Score out of range: " + score);
        }
    }
}

Checked Custom Exception

For a custom checked exception, extend the Exception class instead of RuntimeException. All other steps remain identical. The compiler will then require callers to either catch or declare the exception.

Tags: java Exception Handling Error Handling Custom Exception

Posted on Sun, 17 May 2026 03:20:25 +0000 by mrclark219