DEV Community

Cover image for Exception Handling
Abinesh.R
Abinesh.R

Posted on

Exception Handling

Exception Handling in Java
1. What is an exception?

An exception is an event that disrupts the normal flow of a program at runtime. Exception handling lets the program recover or end gracefully instead of crashing.

2. Exception hierarchy

Throwable
├── Error (serious, don't catch: OutOfMemoryError, StackOverflowError)
└── Exception
├── RuntimeException (unchecked: NullPointerException, ArithmeticException,
│ ArrayIndexOutOfBoundsException, NumberFormatException)
└── Checked exceptions (IOException, SQLException, ClassNotFoundException)
**

  1. Checked vs Unchecked**

    Checked Unchecked
    Checked by Compiler Not checked at compile time
    Must handle? Yes (try-catch or throws) No
    Extends Exception (not RuntimeException) RuntimeException
    Examples SQLException, IOException NullPointerException, ArithmeticException

4. The 5 keywords
try: the code that may throw an exception
catch: handles the exception
finally: always runs (cleanup, such as closing a connection)
throw: manually throws an exception object
throws: declares exceptions a method may pass to its caller

5. try-catch-finally
public class TryCatchDemo {
public static void main(String[] args) {
try {
int a = 10, b = 0;
int result = a / b; // throws ArithmeticException
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Finally always runs");
}
System.out.println("Program continues...");
}
}
**

  1. Multiple catch blocks and multi-catch**

public class MultiCatchDemo {
public static void main(String[] args) {
try {
String s = null;
int[] arr = new int[3];
arr[5] = 10; // ArrayIndexOutOfBoundsException
System.out.println(s.length());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index problem");
} catch (NullPointerException e) {
System.out.println("Null problem");
} catch (Exception e) { // parent class always LAST
System.out.println("General: " + e);
}

    // Multi-catch (Java 7+)
    try {
        Integer.parseInt("abc");
    } catch (NumberFormatException | NullPointerException e) {
        System.out.println("Multi-catch: " + e.getMessage());
    }
}
Enter fullscreen mode Exit fullscreen mode

}

Rule: child exceptions must come before parent exceptions, or you get a compile error.
**

  1. throw vs throws**

public class ThrowDemo {

// throws: declares that this method may pass the exception to the caller
static void checkAge(int age) throws Exception {
    if (age < 18) {
        throw new Exception("Not eligible to vote");   // throw: creates and throws
    }
    System.out.println("Eligible to vote");
}

public static void main(String[] args) {
    try {
        checkAge(15);
    } catch (Exception e) {
        System.out.println("Caught: " + e.getMessage());
    }
}
Enter fullscreen mode Exit fullscreen mode

}

throw ** throws**
Used inside a method body Used in the method signature
Throws one exception object Can declare multiple exceptions
Followed by an object (new ...) Followed by class names

class InvalidVoterException extends Exception {
public InvalidVoterException(String message) {
super(message);
}
}

public class CustomExceptionDemo {
static void verifyVoter(int age) throws InvalidVoterException {
if (age < 18) {
throw new InvalidVoterException("Voter must be 18 or older");
}
System.out.println("Voter verified");
}

public static void main(String[] args) {
    try {
        verifyVoter(16);
    } catch (InvalidVoterException e) {
        System.out.println("Custom exception: " + e.getMessage());
    }
}
Enter fullscreen mode Exit fullscreen mode

}

Extend Exception for a checked custom exception, or RuntimeException for an unchecked one.

9. try-with-resources (Java 7+)
Resources that implement AutoCloseable (such as Connection, Statement, Scanner) are closed automatically, so there is no need for a finally block.

import java.sql.*;

public class TryWithResourcesDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb";
try (Connection con = DriverManager.getConnection(url, "root", "password");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM users")) {

        while (rs.next()) {
            System.out.println(rs.getString(1));
        }
    } catch (SQLException e) {
        System.out.println("DB error: " + e.getMessage());
    }
}
Enter fullscreen mode Exit fullscreen mode

}

10. Important rules (interview points)

finally runs even when there is a return in try. The only exceptions are System.exit() and a JVM crash.
A try block must have at least one catch or a finally.
Parent exception catch blocks must come after child catch blocks.
In method overriding, the overriding method cannot throw a broader checked exception than the parent method.
Error is not meant to be caught. It indicates a serious JVM problem.
Use e.printStackTrace() for debugging, e.getMessage() for the message.
Exception chaining: throw new CustomException("msg", e); keeps the original cause.

11. Common exceptions quick list
Exception Cause
ArithmeticException Division by zero
NullPointerException Using a null reference
ArrayIndexOutOfBoundsException Invalid array index
NumberFormatException Integer.parseInt("abc")
ClassCastException Invalid type cast
FileNotFoundException File doesn’t exist
SQLException JDBC or database error
ClassNotFoundException Class not found (e.g., JDBC driver)

12. Run any example

javac TryCatchDemo.java
java TryCatchDemo

Hierarchy of Java Exceptions

Top comments (0)