Java - Java Exceptions
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
throwsthe exception orcatchthe 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) {
//...
}