Java Core
    Java - Overview
    What is new in Java 21
    What is new in Java 17
    What is new in Java 11
    Java - JVM
    Java - Deprecated
    Java - Numbers
    Java - String
    Java - Time
    Java - Collections
    Java - Lambda
    Java - Exceptions
    Java - Switch
    Java - IO
    Java - Jar
    Java - Generics
    Java - Environment
    Java - Concurrency
    Java - Trouble Shooting
    Java - Install
    Java - Misc

Java - Java Exceptions

Updated: 2021-11-19

Java Errors and Exceptions

Both Error and Exception are Throwables.

  • Checked Exceptions:
    • exception handling is checked at compile time; exception must be explicitly defined on the method definition; the caller must either throws the exception or catch the exception and deal with it
    • e.g. IOException
  • Unchecked Exceptions:
    • exception handling is NOT verified during compile time. Internal, incorrect use of API, logic error
    • e.g. RuntimeException, ArrayIndexOutOfBoundsException, NullPointerException
  • Error: something cannot recover from, external, JVM. Also unchecked. e.g. NoClassDefFoundError, OutOfMemoryError.

Effective Java recommends using only unchecked exceptions.

Modern languages such as Scala have stepped away from checked exceptions, and have only runtime exceptions.

try-with-resources

Since Java 7:

try (BufferedWriter writer = Files.newBufferedWriter(path, charset)) {
    //...
}

Resources must implement java.lang.AutoCloseable.

Catching Multiple Exception

Since Java 7:

try {
    //...
} catch (IOException | SQLException e) {
    //...
}