Home >Java >javaTutorial >Using multiple catch statements
Multiple catch statements:
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:
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:
Conclusion:
The above is the detailed content of Using multiple catch statements. For more information, please follow other related articles on the PHP Chinese website!