Junior
Tell me about the exception hierarchy in Java.
sobes.tech AI
Answer from AI
The exception hierarchy in Java is based on the Throwable class.
Main subclasses of Throwable:
Error: Represents serious problems that the application usually cannot recover from (e.g.,OutOfMemoryError,StackOverflowError). They are not meant to be caught and handled in regular application code.Exception: Represents conditions that the application might attempt to recover from.RuntimeException: A subclass ofException, representing runtime exceptions (e.g.,NullPointerException,ArrayIndexOutOfBoundsException). The compiler does not require them to be declared or caught (unchecked exceptions).- Other subclasses of
Exception: Checked exceptions (e.g.,IOException,SQLException). The compiler requires them to be declared in the method signature (throws) or caught (try-catch).
Hierarchy structure:
Throwable
├── Error
│ ├── LinkageError
│ ├── VirtualMachineError
│ └── ...
│
└── Exception
├── RuntimeException
│ ├── NullPointerException
│ ├── IndexOutOfBoundsException
│ └── ...
└── IOException
├── FileNotFoundException
└── ...
└── SQLException
└── ...
Key differences between Error, RuntimeException, and checked Exception:
| Exception Type | Checked? | What does it represent? | Examples |
|---|---|---|---|
Error |
No | Serious system problems | OutOfMemoryError |
RuntimeException |
No | Logic errors in the program | NullPointerException |
Checked Exception |
Yes | Expected but undesirable events | IOException, SQLException |
Exception handling principle:
try-catch-finallyblocks are used for exception handling.- Exceptions can be caught by their class. Catching a more general class also catches its subclasses.
- The order of
catchblocks is important: more specific exceptions should be caught before more general ones.
// Example of exception handling
try {
// Code that may generate an exception
int result = 10 / 0; // Example ArithmeticException (RuntimeException)
} catch (ArithmeticException e) {
// Handling specific exception
System.err.println("Division by zero occurred: " + e.getMessage());
} catch (RuntimeException e) {
// Handling more general runtime exception
System.err.println("Runtime error occurred: " + e.getMessage());
} catch (Exception e) {
// Handling any other Exception
System.err.println("A general error occurred: " + e.getMessage());
} finally {
// Code that always executes, regardless of exception
System.out.println("Finally block executed.");
}
Creating custom exceptions:
- Usually inherit from
Exception(for checked) orRuntimeException(for unchecked).