自行处理
1.try{//可能发生异常的代码 }catch(异常类 变量名){//处理}。
2.案例除法运算的异常处理。
3.如果没有进行try catch处理,出现异常程序就停止。进行处理后,程序会继续执行。
class Demo { publicstaticvoidmain(String[] args) { div(2, 0); System.out.println("over"); } publicstaticvoiddiv(int x, int y) { try { System.out.println(x / y); // 可能出现异常的语句,放入try中。 } catch (ArithmeticException e) { // 进行异常匹配,//异常信息 System.out.println(e.toString()); System.out.println(e.getMessage()); e.printStackTrace(); System.out.println("除数不能为0"); } System.out.println("除法运算"); }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
多个异常
1.案例print方法,形参中增加数组。
2.在print方法中操作数组会发生新的异常ArrayIndexOutOfBoundsException,NullPointerException),如何处理?
1.使用将可能发生异常的代码放入try语句中,添加多个catch语句即可。
2.可以处理多种异常,但是同时只能处理一种异常。
3.try中除0异常和数组角标越界同时出现,只会处理一种。
publicclass Demo{ publicstaticvoidmain(String[] args) { System.out.println(); int[] arr = { 1, 2 }; arr = null; // print (1, 0, arr); print (1, 2, arr); System.out.println("over"); } publicstaticvoidprint(int x, int y, int[] arr) { try { System.out.println(arr[1]); System.out.println(x / y); } catch (ArithmeticException e) { e.toString(); e.getMessage(); e.printStackTrace(); System.out.println("算术异常。。。"); } catch (ArrayIndexOutOfBoundsException e) { e.toString(); e.getMessage(); e.printStackTrace(); System.out.println("数组角标越界。。。"); } catch (NullPointerException e) { e.toString(); e.getMessage(); e.printStackTrace(); System.out.println("空指针异常。。。"); } System.out.println("函数执行完毕"); }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
总结
1.程序中有多个语句可能发生异常,可以都放在try语句中。并匹配对个catch语句处理。
2.如果异常被catch匹配上,接着执行try{}catch(){} 后的语句。没有匹配上程序停止。
3.try中多个异常同时出现,只会处理第一条出现异常的一句,剩余的异常不再处理。
4.使用多态机制处理异常。1.程序中多态语句出现不同异常,出现了多个catch语句。简化处理(相当于急诊)。
2.使用多态,使用这些异常的父类进行接收。(父类引用接收子类对象)
publicstaticvoiddiv(int x, int y, int[] arr, Father f) { try { System.out.println(arr[1]); // 数组越界 System.out.println(x / y); // 除零 Son s = (Son) f; // 类型转换 } catch (Exception e) { e.toString(); e.getMessage(); e.printStackTrace(); System.out.println("出错啦"); } System.out.println("函数执行完毕"); }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
多个catch语句之间的执行顺序。
1.是进行顺序执行,从上到下。
2.如果多个catch 内的异常有子父类关系。1.子类异常在上,父类在最下。编译通过运行没有问题
2.父类异常在上,子类在下,编译不通过。(因为父类可以将子类的异常处理,子类的catch处理不到)。
3.多个异常要按照子类和父类顺序进行catch
classFather {}classSonextendsFather {}publicclassDemo8 {publicstaticvoid main(String[] args) { Syste