白小白的日志

一个菜鸡的心酸之路....

导航

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");
}
}

 

posted on 2022-08-01 09:18  白小白的日志  阅读(15)  评论(0)    收藏  举报