一、案例演示(除数为0运行时异常)
1、创建一个名为RuntimeExceptionDemo的类
编写代码时未报错,点击运行,运行结果如下,报异常:
2、使用try/catch捕捉异常
package introduction8; public class RuntimeExceptionDemo { public static void main(String[] args) { int a = 10; int b = 0; int c; try { c = a/b; System.out.println("计算结果为:"+c); }catch(ArithmeticException e) { System.out.println(e.getMessage()); } } }
运行结果:
二、案例演示(角标越界运行时异常)
运行结果:
使用try/catch捕捉异常
package introduction8; public class RuntimeExceptionDemo { public static void main(String[] args) { /* //除数为0 int a = 10; int b = 0; int c; try { c = a/b; System.out.println("计算结果为:"+c); }catch(ArithmeticException e) { System.out.println(e.getMessage()); System.out.println("0不能为除数"); } */ //角标越界 int[] numbers = {1,2,3}; try { for(int i = 0;i<=3;i++) { System.out.println(numbers[i]); } } catch (ArrayIndexOutOfBoundsException e) { System.out.println("角标"+e.getMessage()+"越界情况"); } } }