Exception Handling With the Chain Of Responsibility
This overview of exception handling covers an overview of how handling should work and explores how to use a chain of responsibility for your exceptions.
Join the DZone community and get the full member experience.Join For Free
An exception (or exceptional event) is a problem that arises during the execution of a program. When an exception occurs, the normal flow of the program is disrupted and the program/application terminates abnormally, which is not recommended. Therefore, these exceptions are to be handled.
An exception can occur for many different reasons. The following are some scenarios where an exception occurs.
- A user has entered invalid data.
- A file that needs to be opened cannot be found.
- A network connection has been lost in the middle of communications or the JVM has run out of memory.
Based on these, we have three categories of exceptions. You need to understand them to know how exception handling works in Java.
According to Item 58 - Use checked exceptions for recoverable conditions and runtime exceptions for programming errors, from Effective Java 2/e by Joshua Bloch, the Java programming language provides three kinds of throwables.
Checked exceptions: Use exceptions for conditions from which the caller can reasonably be expected to recover.
Runtime exceptions (unchecked exceptions): Use exceptions to indicate programming errors. All of the unchecked throwables you implement should use subclass RuntimeException
We can view Chain Of Responsibility — Design Pattern for this purpose.
Example: When an exception is thrown in a method, the runtime checks to see if the method has a mechanism to handle the exception or if it should be passed up the call stack. When passed up the call stack, the process repeats until the code to handle the exception is encountered or until there are no more parent objects to hand the request to.
For see the source code on GitHub, please refer to this link.
Opinions expressed by DZone contributors are their own.