多个 catch 语句:
处理不同异常的示例:
以下程序捕获两种类型的异常:
ArithmeticException(除以零)。
ArrayIndexOutOfBoundsException(超出数组范围的访问)。
代码示例:
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."); } } } }
程序输出:
示例输出:
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.
catch 块的执行:
每个捕获都会按照其在代码中出现的顺序进行检查。
仅执行与发现的异常类型对应的catch,其他的将被忽略。
使用多个 catch 的优点:
结论:
以上是使用多个 catch 语句的详细内容。更多信息请关注PHP中文网其他相关文章!