9.异常
异常:
1.编译异常
FileNotFoundException
SQLException
ClassNotFoundException
InterruptException
2.运行异常
数组下标越界 ArrayIndexOutOfBoundException
类转换异常 ClassCastException
空指针异常 NullPointerException
异常的捕捉:
public class Demo2 { public static void main(String[] args) { test(10, 0); } public static void test (int a, int b) { int num = 0 ; try { num = a / b ; } catch (Exception e) { System.out.println(e.getMessage()); System.out.println("有异常状况出现!!!"); } //就算代码有问题,也会执行程序的后续操作 System.out.println(num); } }
异常的抛出:
1.throw : 在方法中抛出一个异常,自己造一个错
2.throws : 在方法的声明处书写,用于告知调用者,这里有异常,要注意。
public class Demo3 { public static void main(String[] args) throws Exception { test(0); } public static void test(int a) throws Exception{ if (a == 0) { //符合条件 编译异常 throw new Exception(); } System.out.println("jvm 12121212121"); } }
浙公网安备 33010602011771号