Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Multiple Catch Blocks | Handling Exceptions in Java
Quizzes & Challenges
Quizzes
Challenges
/
Exceptions and Error Handling in Java

bookMultiple Catch Blocks

When working with exceptions in Java, you often need to handle different types of errors that may occur in your code. Multiple catch blocks allow you to respond to various exception types separately within a single try-catch structure. By placing several catch blocks after a try block, you can specify unique handling logic for each exception class. This approach makes your code more robust, as you can address specific problems such as input errors, arithmetic mistakes, or null references differently, depending on the situation.

try {
    // code
} catch (Exception1) {
    // exception handling 1
} catch (Exception2) {
    // exception handling 2
}

The order of catch blocks is crucial because Java checks each catch block in sequence, from top to bottom, to find a matching exception type.

Since exceptions are organized in a hierarchy, a catch block for a superclass exception (like Exception) must always come after catch blocks for its subclasses (such as NullPointerException or ArithmeticException).

If a superclass catch block appears before its subclasses, the compiler will generate an error, because the subclass catch blocks would become unreachable. Understanding this hierarchy ensures that your program handles exceptions in the most precise way possible.

Main.java

Main.java

copy
12345678910111213141516
package com.example; public class Main { public static void main(String[] args) { try { int[] numbers = {1, 2, 3}; System.out.println("Result: " + (10 / numbers[3])); } catch (ArithmeticException e) { System.out.println("ArithmeticException caught: " + e.getMessage()); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBoundsException caught: " + e.getMessage()); } catch (Exception e) { System.out.println("General Exception caught: " + e.getMessage()); } } }

In the program above, the try block attempts to divide 10 by the value at index 3 of the numbers array. However, since the array only has three elements (indices 0, 1, and 2), accessing numbers[3] will throw an ArrayIndexOutOfBoundsException.

When an exception occurs, Java checks each catch block in order. It first looks for an ArithmeticException, then an ArrayIndexOutOfBoundsException, and finally a general Exception. Because the thrown exception matches ArrayIndexOutOfBoundsException, only that catch block executes, and the others are skipped. This demonstrates how Java chooses the most specific matching catch block, ensuring that the exception is handled appropriately.

question mark

Why does the order of catch blocks matter when handling exceptions in Java?

Select the correct answer

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 2. Kapitel 2

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Awesome!

Completion rate improved to 10

bookMultiple Catch Blocks

Svep för att visa menyn

When working with exceptions in Java, you often need to handle different types of errors that may occur in your code. Multiple catch blocks allow you to respond to various exception types separately within a single try-catch structure. By placing several catch blocks after a try block, you can specify unique handling logic for each exception class. This approach makes your code more robust, as you can address specific problems such as input errors, arithmetic mistakes, or null references differently, depending on the situation.

try {
    // code
} catch (Exception1) {
    // exception handling 1
} catch (Exception2) {
    // exception handling 2
}

The order of catch blocks is crucial because Java checks each catch block in sequence, from top to bottom, to find a matching exception type.

Since exceptions are organized in a hierarchy, a catch block for a superclass exception (like Exception) must always come after catch blocks for its subclasses (such as NullPointerException or ArithmeticException).

If a superclass catch block appears before its subclasses, the compiler will generate an error, because the subclass catch blocks would become unreachable. Understanding this hierarchy ensures that your program handles exceptions in the most precise way possible.

Main.java

Main.java

copy
12345678910111213141516
package com.example; public class Main { public static void main(String[] args) { try { int[] numbers = {1, 2, 3}; System.out.println("Result: " + (10 / numbers[3])); } catch (ArithmeticException e) { System.out.println("ArithmeticException caught: " + e.getMessage()); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBoundsException caught: " + e.getMessage()); } catch (Exception e) { System.out.println("General Exception caught: " + e.getMessage()); } } }

In the program above, the try block attempts to divide 10 by the value at index 3 of the numbers array. However, since the array only has three elements (indices 0, 1, and 2), accessing numbers[3] will throw an ArrayIndexOutOfBoundsException.

When an exception occurs, Java checks each catch block in order. It first looks for an ArithmeticException, then an ArrayIndexOutOfBoundsException, and finally a general Exception. Because the thrown exception matches ArrayIndexOutOfBoundsException, only that catch block executes, and the others are skipped. This demonstrates how Java chooses the most specific matching catch block, ensuring that the exception is handled appropriately.

question mark

Why does the order of catch blocks matter when handling exceptions in Java?

Select the correct answer

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 2. Kapitel 2
some-alt