Java - Java Exceptions
Last Updated: 2021-11-19
Java Errors and Exceptions
Both Error
and Exception
are Throwable
s.
- 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 orcatch
the exception and deal with it - e.g.
IOException
- exception handling is checked at compile time; exception must be explicitly defined on the method definition; the caller must either
- 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) {
//...
}