异常处理允许程序连续性:
捕获异常的示例:
代码示例:
class ExcDemo3 { public static void main(String args[]) { int numer[] = { 4, 8, 16, 32, 64, 128 }; 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!"); } } } }
程序输出:
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
异常处理后会被移除:
好处:
异常处理允许程序处理重复的错误并顺利地继续执行流程。
结论:
异常处理允许程序通过处理除零等错误来继续运行,而不是终止执行。
以上是异常可以让你正常处理错误的详细内容。更多信息请关注PHP中文网其他相关文章!