Exception Hanlding in Java
Checked and Unchecked Exception and how to handle exceptions in Java.
Checked Exception
Checked exceptions are subclasses of Exception.
Checked Exception are the exceptions that are checked at compile time. If a method throws a checked exception, the caller must handle the exception or declare the exception in the method signature. For example, IOException, SQLException are checked exceptions.
Use checked exceptions when the caller can recover from the exception. For example, if a file is not found, the caller can handle the exception by creating a new file.
Some programming languages like C# and Python do not have checked exceptions. They use unchecked exceptions for all exceptions.
Checked Exception example:
1 | public class NewCheckedException extends Exception { |
Unchecked Exception(Runtime Exception)
Unchecked exceptions are subclasses of RuntimeException.
Unchecked Exception are the exceptions that are not checked at compile time. If a method throws an unchecked exception, the caller is not required to handle the exception. For example, NullPointerException, ArrayIndexOutOfBoundsException are unchecked exceptions. Unchecked exceptions are usually bubbled up to the top of the call stack.
Use unchecked exceptions when the caller cannot recover from the exception. For example, if a user is not found, the caller cannot recover from the exception.
Unchecked Exception example:
1 | public class UserNotFoundException extends RuntimeException { |
Handle Exception
There are a couple of ways to handle exceptions in Java.
- log the exception and continue if the exception is not critical
- log and rethrow the exception
- wrap the exception and rethrow the exception
Remeber not to ignore/swallow the exception.
Checked exception produces a lot of boilerplate code. It is common to wrap the checked exception in an unchecked exception and rethrow the exception.