Java
Multiple catch
Learn multiple catch blocks.
Multiple catch blocks
A single try can be followed by multiple catch blocks. Each catches a different exception type. Order matters: specific types come first, general types later.
try {
int n = Integer.parseInt(s);
int r = 10 / n;
} catch (NumberFormatException e) {
System.out.println("Sayı değil");
} catch (ArithmeticException e) {
System.out.println("Sıfıra bölme");
}
If you put a general type first, the specific ones become unreachable and you get a compile error. So you must place general types like Exception last. Each catch is independent; only one runs.
Multi-catch
Since Java 7 you can catch multiple types in a single catch. Types are separated by |; this is called multi-catch.
try {
int n = Integer.parseInt(s);
} catch (NumberFormatException | ArithmeticException e) {
System.out.println("Hata");
}
Multi-catch avoids code duplication for different types that need the same handling. However, the types separated by | cannot be related by inheritance; they must be siblings. The e variable is implicitly final; it cannot be modified inside.
Exercise Catch two types with separate catch
Define String s = "abc";. Inside try write Integer.parseInt(s) and int r = 10 / n;. The first catch catches NumberFormatException and prints Sayı değil; the second catches ArithmeticException and prints Sıfıra bölme.
Show example solution
try {
int n = Integer.parseInt(s);
int r = 10 / n;
System.out.println(r);
} catch (NumberFormatException e) {
System.out.println("Sayı değil");
} catch (ArithmeticException e) {
System.out.println("Sıfıra bölme");
}
Test yourself
-
Add the second catch
try {
int n = Integer.parseInt(s);
} catch (NumberFormatException e) {
System.out.println("Sayı değil");
} ____ (ArithmeticException e) {
System.out.println("Sıfıra bölme");
}
Show answer
try {
int n = Integer.parseInt(s);
} catch (NumberFormatException e) {
System.out.println("Sayı değil");
} catch (ArithmeticException e) {
System.out.println("Sıfıra bölme");
}
-
How should multiple catch blocks be ordered?
- General first, then specific
- Specific first, then general
- Only one catch is allowed
- Order does not matter
Show answer
Specific first, then general — specific types come first; general types go last, otherwise a compile error occurs.
-
Match each scenario to its catch type
- parseInt fails
- NumberFormatException
- division by zero
- ArithmeticException
- null object
- NullPointerException
- out of bounds
- ArrayIndexOutOfBoundsException
Next lesson: Summary - Exception basics