Junior — Middle
Explain the exception hierarchy in Java and how it is used in error handling.
sobes.tech AI
Answer from AI
In Java, the exception hierarchy is built from the base class Throwable, which has two main subclasses: Error and Exception.
- Error — serious errors that are usually not handled by the application (e.g.,
OutOfMemoryError). - Exception — exceptions that can and should be handled.
In turn, Exception is divided into:
- Checked exceptions — require mandatory handling or declaration in the method (
IOException,SQLException). - Unchecked exceptions — descendants of
RuntimeException, which do not require handling (NullPointerException,IllegalArgumentException).
Error handling uses a try-catch block, where exceptions can be caught at different levels of the hierarchy. For example, you can catch a specific exception or a more general one to ensure flexibility and safety of the code.
try {
// code that may throw an exception
} catch (IOException e) {
// handle specific exception
} catch (Exception e) {
// handle all other exceptions
}