Question
How does exception handling work for RuntimeException in Java?
catch (Exception exc) { /* won't catch RuntimeException */ }
Answer
In Java, the exception handling mechanism is based on a hierarchy of classes, with Exception being a checked exception and RuntimeException being an unchecked exception. Understanding the distinction between these two is crucial for proper error handling in applications.
for (Callback cb : callbacks) {
try {
cb.call(item);
} catch (Exception exc) {
logger.error("Error in callback: ", exc);
}
}
Causes
- RuntimeException is a subclass of Exception and is therefore part of its hierarchy.
- The distinction lies in the fact that RuntimeExceptions are unchecked exceptions, meaning they do not need to be declared in method signatures and are not enforced at compile time.
Solutions
- To catch both checked and unchecked exceptions, use a larger scope of exception types such as Throwable, which encompasses all exceptions.
- For specific cases where only RuntimeExceptions are expected but you want to provide isolation among callbacks, you can catch Exception for checked exceptions and handle RuntimeException separately.
- Alternatively, consider implementing a custom callback interface that includes error handling for the specific situations you're encountering.
Common Mistakes
Mistake: Catching Exception but not RuntimeException when necessary.
Solution: Make sure to catch RuntimeException if you want to handle it specifically or ensure that critical failures are considered.
Mistake: Assuming catching Throwable provides no additional issues than catching Exception.
Solution: Catching Throwable can mask serious errors, such as OutOfMemoryError; use it judiciously.
Helpers
- Java exception handling
- RuntimeException vs Exception
- Java try-catch
- Unchecked exceptions
- Checked exceptions
- Java best practices for exceptions