SwadhyAI Notes

All Java notes

Java Errors & Exceptions Reference

›Short versionOpen if you only have a minute.
  • Throwable splits into Exception and Error. Error is for failures the program usually should not catch.
  • A checked exception, such as IOException, must be caught or listed in throws. The compiler enforces that.
  • RuntimeException and its subclasses are unchecked. NullPointerException and IllegalArgumentException are in that group.
  • catch clauses are tested in order. A broader type written first makes a later narrower catch unreachable.
  • finally runs after try and catch, including when the try block returns. A return inside finally replaces that result.
  • try-with-resources closes the resource and can attach a close failure as a suppressed exception.

Exceptions are objects that interrupt normal control flow. Checked exceptions must be handled or declared; unchecked exceptions usually signal programming errors or invalid runtime state.

Methods

APIParametersReturnsBehaviorWatch for
try { ... } catch (...) { ... }Risky block and one or more handlers.Normal result from handled control flow.Transfers control to the first compatible catch block.Order catch blocks from most specific to most general.
finally { ... }Cleanup statements.No direct value.Runs after try/catch in most circumstances.Avoid return statements in finally because they can hide exceptions.
throw new Exception(...)Throwable instance.Does not return normally.Raises an exception at the current point.Throw meaningful exception types with useful messages.
throws IOExceptionMethod declaration list of possible checked exceptions.Contract to the caller.Propagates handling responsibility to callers.Declaring broad Exception makes APIs harder to use.
getMessage()None.Detail message or null.Provides human-readable failure detail.Do not parse messages for program logic.
printStackTrace()Optional PrintStream or PrintWriter overloads.void.Prints stack trace for debugging.Use logging in real applications instead of printing directly.

Which call fits

OptionBest forTradeoff
Checked exceptionRecoverable conditions callers can reasonably handle, such as IOException.Adds throws declarations or catch blocks.
Unchecked exceptionProgramming mistakes and invalid arguments.Can appear at runtime without compiler enforcement.
ErrorSerious JVM or environment problems.Usually should not be caught by application code.

Examples

Catch specific failures

java
try {
    int value = Integer.parseInt(input);
    System.out.println(value);
} catch (NumberFormatException e) {
    System.out.println("Please enter a valid integer.");
}

Declare or handle checked exceptions

java
static String firstLine(String path) throws IOException {
    try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
        return reader.readLine();
    }
}

try throws IOException, and finally returns 0. What does the caller receive?

The value 0. The IOException does not propagate, because the return in finally completed the method normally. The caller has no exception to catch and no stack trace from the failure inside try. A catch (Exception) written above a catch (IOException) is a different mistake: the second clause is unreachable, and the file does not compile.