Q: What is Java Exception?
An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.
Q: When to use Custom Exceptions?
You should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else's.
- Do you need an exception type that isn't represented by those in the Java platform?
- Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors?
- Does your code throw more than one related exception?
- If you use someone else's exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-contained?
Q: When to use Runtime vs. Checked Exceptions?
If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
Q: When to propagate Exception vs. handle locally?
It depends on your application requirement. If the application layer where exception is thrown (or propagated from lower layer) can handle the exception and does need to inform upper layer about it, it can have exception handling here. But if the application layer cannot handle (or recover) the exception and upper layer is right place to be informed and handle the exception then better re-throw (or pass) the exception.
Few more best practices:
- Avoid catching top level exceptions.
- Log exceptions just once.
- Never let implementation-specific checked exceptions escalate to the higher layers. For example, do not propagate SQLException from data access code to the business objects layer. Business objects layer do not need to know about SQLException. We have two options here: (1) Convert SQLException into another checked exception, if the client code is expected to recover from the exception. (2) Convert SQLException into an unchecked exception, if the client code cannot do anything about it.