Senior
Describe the basic hierarchy of exceptions in Java. What are checked and unchecked exceptions?
sobes.tech AI
Answer from AI
In Java, the exception hierarchy starts with the Throwable class, which has two main subclasses:
- Error — errors that are usually not handled by the application (e.g., OutOfMemoryError).
- Exception — exceptions that can be handled.
In turn, Exception is divided into:
- Checked exceptions — exceptions that the compiler requires to be either handled (try-catch) or declared in the method signature (throws). Examples: IOException, SQLException.
- Unchecked exceptions — subclasses of RuntimeException that do not require mandatory handling. Examples: NullPointerException, IllegalArgumentException.
Checked exceptions are used for situations that can be foreseen and handled, such as input/output errors. Unchecked exceptions are for programming errors or unforeseen situations.
Example:
public void readFile(String path) throws IOException {
// checked exception
}
public void processData(Object obj) {
if (obj == null) {
throw new NullPointerException(); // unchecked
}
}