Home  >  Article  >  Java  >  Using multiple catch statements

Using multiple catch statements

DDD
DDDOriginal
2024-10-19 14:08:31732browse

Usando várias instruções catch

Multiple catch statements:

  • A try block can be associated with multiple catch statements to catch different types of exceptions.
  • Each catch handles a specific exception.

Example with handling different exceptions:

The following program catches two types of exceptions:
ArithmeticException (division by zero).
ArrayIndexOutOfBoundsException (access outside the bounds of the array).

Code example:

class ExcDemo4 {
    public static void main(String args[]) {
        // O array numer é maior que denom.
        int numer[] = { 4, 8, 16, 32, 64, 128, 256, 512 };
        int denom[] = { 2, 0, 4, 4, 0, 8 };

        for (int i = 0; i < numer.length; i++) {
            try {
                // Tenta realizar a divisão
                System.out.println(numer[i] + " / " + denom[i] + " is " + numer[i] / denom[i]);
            } catch (ArithmeticException exc) {
                // Captura e trata a exceção de divisão por zero
                System.out.println("Can't divide by Zero!");
            } catch (ArrayIndexOutOfBoundsException exc) {
                // Captura e trata a exceção de acesso fora dos limites do array
                System.out.println("No matching element found.");
            }
        }
    }
}

Program output:

  • The program displays the results of correct divisions.
  • When a division by zero occurs, it is handled.
  • When denom index does not exist, array limit exception is handled.

Example output:

4 / 2 is 2
Can't divide by Zero!
16 / 4 is 4
32 / 4 is 8
Can't divide by Zero!
128 / 8 is 16
No matching element found.
No matching element found.

Execution of catch blocks:
Each catch is checked in the order it occurs in the code.
Only the catch corresponding to the type of exception found will be executed, while the others will be ignored.

Advantage of using multiple catches:

  • Allows you to handle different types of exceptions in a specific way, making the code more robust.

Conclusion:

  • Using multiple catch statements makes it possible to catch different types of exceptions, handle them appropriately, and allow the program to continue executing even when errors occur.

The above is the detailed content of Using multiple catch statements. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn