Working With Exceptions Slides
Working With Exceptions Slides
Esteban Herrera
JAVA ARCHITECT
@eh3rrera http://eherrera.net
Catch block rules
Overview Multi-catch block
Finally block
Try-with-resources block
Rethrowing and chaining exceptions
Throws clause
Catch Block Rules
Demo
http://bit.ly/jls11-2
Three Important Rules
// ...
}
The Multi-catch Block
try {
// ...
} catch (IOException e) {
log.error(e);
} catch (SQLException e) {
log.error(e);
} catch (ClassCastException e) {
log.error(e);
Before Java 7…
try {
// ...
log.error(e);
After Java 7…
try {
Multi-catch
Demo
Multi-catch block
Three Important Rules
} catch(Exception e) {
} finally {
Finally Block
try {
} finally {
Finally Block
try {
// ...
// ...
} finally {
Without executing the finally
// ... block
}
Demo
Finally block
If the finally block completes abruptly
for reason S, then the try statement
completes abruptly for reason S (and
reason R is discarded).
The Java® Language Specification 14.20.2
http://bit.ly/jls14-20-2
Three Important Rules
} catch(Exception e) {
} finally {
Try-with-resources Block
try (AutoCloseableResource r = new AutoCloseableResource()) {
} catch(Exception e) {
Try-with-resources Block
try (AutoCloseableResource r = new AutoCloseableResource()) {
Try-with-resources Block
try (AutoCloseableResource r = new AutoCloseableResource();
Try-with-resources Block
Interfaces to Implement by Resources
java.lang.AutoCloseable
java.io.Closeable
http://bit.ly/autocloseabledoc
http://bit.ly/closeabledoc
void close() throws IOException;
java.io.Closeable
void close() throws Exception;
java.lang.AutoCloseable
Demo
Try-with-resources block
Three Important Rules
// and ExceptionThree
Throws Clause
Demo
Throws clause
Three Important Rules
Handled or declared.
Mix subclasses and superclasses.
Only throw the specified checked
exceptions when overriding.
Catch block rules
Summary Multi-catch block
Finally block
Try-with-resources block
Rethrowing and chaining exceptions
Throws clause