Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

Java Exception Handling: try-catch, Checked vs Unchecked and Best Practices

Master Java exception handling: the exception hierarchy, checked vs unchecked exceptions, try-catch-finally, try-with-resources, custom exceptions and the best practices senior developers follow.

Sumit KumarUpdated Oct 11, 20264 min readJava
Java Exception Handling: try-catch, Checked vs Unchecked and Best Practices

An exception is an event that interrupts the normal flow of a program: a missing file, a bad input, a lost network connection. Java gives you a structured way to signal these problems and recover from them, and handling them well is the difference between a crash and a helpful error message.

The exception hierarchy#

Java exception hierarchy: Throwable splits into Error, checked exceptions and RuntimeException

Everything that can be thrown extends Throwable, which has two branches:

  • Error: serious problems in the JVM itself, like OutOfMemoryError or StackOverflowError. Your code normally shouldn't catch these.
  • Exception: problems your application can reasonably handle. These split further into checked and unchecked exceptions.

Checked vs unchecked exceptions#

CheckedUnchecked
ExtendsException (but not RuntimeException)RuntimeException
Compiler forces handling?Yes: catch it or declare throwsNo
Typical causeOutside world: files, network, databaseProgramming bugs: null, bad index, invalid argument
ExamplesIOException, SQLExceptionNullPointerException, IllegalArgumentException
Java
// Checked: won't compile unless handled or declared
public String readConfig(Path path) throws IOException {
    return Files.readString(path);
}

// Unchecked: compiles fine, fails at runtime
int[] numbers = new int[3];
numbers[5] = 10;   // ArrayIndexOutOfBoundsException

try, catch and finally#

Java
try {
    int result = divide(10, 0);
    System.out.println(result);
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero: " + e.getMessage());
} finally {
    System.out.println("This always runs");
}
  • The try block holds code that might fail.
  • Each catch block handles one exception type. Java checks them top to bottom, so put more specific types first.
  • The finally block runs whether an exception happened or not. It's for cleanup.

Catching several types#

Java
try {
    process(file);
} catch (FileNotFoundException e) {
    log.warn("File missing: {}", file);
} catch (IOException | ParseException e) {   // multi-catch
    log.error("Could not process {}", file, e);
}

try-with-resources#

Files, database connections and network sockets must be closed even when something fails. Before Java 7 that meant a messy finally block. Now any class that implements AutoCloseable can be closed automatically:

Java
try (BufferedReader reader = Files.newBufferedReader(Path.of("users.csv"));
     Connection conn = dataSource.getConnection()) {

    String line;
    while ((line = reader.readLine()) != null) {
        saveUser(conn, line);
    }
}   // reader and conn are closed here, in reverse order, even on error
Tip

Always use try-with-resources for anything you open. It's shorter, and it can't forget to close a resource when an exception is thrown halfway through.

throw and throws#

Java
public void withdraw(double amount) {
    if (amount <= 0) {
        throw new IllegalArgumentException("Amount must be positive: " + amount);
    }
    // ...
}

public byte[] download(String url) throws IOException {   // declares a checked exception
    // ...
}

throw raises an exception right now. throws in a method signature warns callers that a checked exception may come out of the method.

Custom exceptions#

Create your own exception when a domain problem deserves its own name and callers might handle it differently.

Java
public class InsufficientFundsException extends RuntimeException {
    private final double shortBy;

    public InsufficientFundsException(double shortBy) {
        super("Insufficient funds: short by " + shortBy);
        this.shortBy = shortBy;
    }

    public double getShortBy() {
        return shortBy;
    }
}

Extend RuntimeException for most application errors. Modern frameworks like Spring use unchecked exceptions almost everywhere, because checked exceptions spread throws clauses through every layer.

Wrapping exceptions without losing the cause#

Java
try {
    return repository.findUser(id);
} catch (SQLException e) {
    throw new UserLookupException("Could not load user " + id, e);  // keep the cause!
}

Passing the original exception as the cause keeps the full stack trace, so you can still see the real root problem in the logs.

Best practices#

  1. Never swallow exceptions. An empty catch block hides bugs for months. At minimum, log it.
  2. Catch specific types. catch (Exception e) also catches bugs like NullPointerException that you didn't mean to handle.
  3. Don't use exceptions for normal control flow. Check map.containsKey() instead of catching an exception when a key is missing. Exceptions are slow to create and hard to follow.
  4. Fail fast. Validate inputs at the start of a method and throw IllegalArgumentException or use Objects.requireNonNull.
  5. Write useful messages. Include the value that caused the failure: "User 42 not found" beats "Not found".
  6. Log or rethrow, not both. Logging and rethrowing at every layer prints the same stack trace five times.
  7. Handle exceptions at the right level. Low-level code usually rethrows; a top-level handler (like a Spring @ControllerAdvice) turns them into user-facing responses.

Anti-patterns to avoid#

Java
// Bad: swallowed exception
try { save(user); } catch (Exception e) { }

// Bad: lost cause
catch (IOException e) { throw new RuntimeException("Failed"); }

// Bad: printStackTrace in production code
catch (IOException e) { e.printStackTrace(); }

// Bad: return inside finally hides the exception
finally { return defaultValue; }

Exceptions also matter a lot in concurrent code, where a failure in one thread can disappear silently. See our Java multithreading guide, and for how this all runs under the hood, read JVM vs JDK vs JRE explained.

Key takeaways#

  • All exceptions extend Throwable; Error is for JVM problems, Exception for application problems.
  • Checked exceptions must be caught or declared; unchecked ones (RuntimeException) usually signal bugs.
  • Use try-with-resources for anything that needs closing.
  • Create custom exceptions for meaningful domain errors and always keep the original cause.
  • Never swallow exceptions, catch specific types, and handle them at the right layer.