What are the types of exceptions in Java? What is a Multi-catch Exception?
sobes.tech AI
Answer from AI
In Java, exceptions are divided into three main types:
-
Checked exceptions — exceptions that are checked by the compiler. They must be either handled in a try-catch block or declared in the method signature with
throws. Examples:IOException,SQLException. -
Unchecked exceptions — subclasses of
RuntimeException. The compiler does not require them to be handled. They are usually related to programming errors, such asNullPointerException,IllegalArgumentException. -
Errors — subclasses of
Error. Usually related to runtime environment problems that should not be caught, such asOutOfMemoryError.
Multi-catch Exception — a feature in Java (since version 7) that allows catching multiple exceptions in a single catch block using the | operator. This simplifies code when the handling for different exceptions is the same.
Example:
try {
// code that may throw IOException or SQLException
} catch (IOException | SQLException ex) {
ex.printStackTrace();
}