异常(Exception)

茴香豆 Lv5

程序对异常做出合理的处理,而不至于程序崩溃。

异常指程序运行中出现的不期而至的各种情况,如:文件找不到、网络连接失败、非法参数等。

异常发生在程序运行期间,它影响了正常的程序执行流程。

  • 检查性异常:最具代表性的检查行异常是用户错误或问题引发的异常,这是程序员无法预见的。例如要打开一个不存在的文件时,一个异常就发生了,这些异常在编译时不能被简单的忽略。
  • 运行时异常:运行时异常是可能被程序员避免的异常。与检查性异常相反,运行时异常可以在编译时被忽略。
  • 错误ERROR:错误不是异常,而是脱离程序员控制的问题。错误在代码中通常被忽略。例如,当栈溢出时,一个错误就发生了,它们是编译也检查不到的。

异常体系结构

Java把异常当作对象来处理,并定义一个基类 Java.lang.Throwable 作为所有异常的超类。

Java-6-1

Error

Error类对象由Java虚拟机生成并抛出,大多数错误与代码编写者所执行的操作无关。

Java虚拟机运行错误(Virtual MachineError),当JVM不再有继续执行操作所需的内存资源时,将出现OutOfMemoryError。这些异常发生时,JVM一般会选择线程终止。

还有发生在虚拟机试图执行应用时,如类定义错误(NoClassDefFoundError)、链接错误(LinkageError)。这些错误是不可查的,因为它们在应用程序的控制和处理能力之外,而且绝大多数是程序运行时不允许出现的状况。

Exception

在Exception分支中有一个重要的子类RuntimeException(运行时异常)

  • ArrayIndexOutOfBoundsException(数组下标越界)
  • NullPointerException(空指针异常)
  • ArithmeticException(算数异常)
  • MissingResourceException(丢失资源)
  • ClassNotFoundException(找不到类)

这些异常一般是由程序逻辑错误引起的,程序应该从逻辑角度尽量避免这类异常的发生。

捕获和抛出异常

异常处理关键字:try、catch、finally、throw、throws

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.exception;

public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;

try { // try监控区域
System.out.println(a/b);
} catch (ArithmeticException e){ // catch 捕获异常
System.out.println("程序出现异常,变量b不能为0");
} finally { // 处理善后问题
System.out.println("finally");
}
// finally 可以不要,假设IO、资源,关闭!
System.out.println("====================");
try { // try监控区域
new Test().a();
} catch (Throwable e){ // catch(想要捕获的异常类型) 捕获异常
System.out.println("程序出现异常");
} finally { // 处理善后问题
System.out.println("finally");
}
System.out.println("====================");
// 假设要捕获多个异常: 从小到大!
try { // try监控区域

if (b == 0){ // throw throws
throw new ArithmeticException(); // 主动抛出异常,一般不在这里使用
}

System.out.println(a/b);


} catch (Error e){ // catch(想要捕获的异常类型) 捕获异常
System.out.println("程序出现异常 Error");
} catch (Exception e){ // catch(想要捕获的异常类型) 捕获异常
System.out.println("程序出现异常 Exception");
} catch (Throwable t){ // catch(想要捕获的异常类型) 捕获异常
System.out.println("程序出现异常 Throwable");
} finally { // 处理善后问题
System.out.println("finally");
}

System.out.println("====================");
try {
new Test().test(1, 0);
} catch (ArithmeticException e) {
throw new RuntimeException(e);
}
}

public void a(){b();}
public void b(){a();}
// 假设这个方法中,处理不了这个异常,在方法上抛出异常
public void test(int a, int b) throws ArithmeticException{
if (b == 0){ // throw throws
throw new ArithmeticException(); // 主动抛出异常, 一般在方法中使用
}
System.out.println(a/b);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.exception;

public class Test2 {
public static void main(String[] args) {
int a = 1;
int b = 0;
// ctrl + alt + t 自动为选中区域生成catch语句
try {
System.out.println(a/b);
} catch (Exception e) {
System.out.println("结束");
System.exit(1);
throw new RuntimeException(e);
} finally {
}
/**
* 结束
*
* 进程已结束,退出代码为 1
*/
}
}

自定义异常及经验小结

自定义异常步骤:

  1. 创建自定义异常类。
  2. 在方法中通过 throw关键字抛出异常对象。
  3. 如果在当前抛出异常的方法中处理异常,可以使用try-catch语句捕获并处理;否则在方法的声明处通过throws关键字指明要抛出给方法调用者的异常,继续进行下一步操作。
  4. 在出现异常方法的调用者中捕获并处理异常。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.exception;

public class MyException extends Exception{
// 传递数字 > 10
private int detail;

public MyException(int a){
this.detail = a;
}

//toString 异常的打印信息
@Override
public String toString() {
return "MyException{" +
"detail=" + detail +
'}';
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.exception;

public class Test3 {
// 可能会存在异常的方法
static void test(int a) throws MyException{
System.out.println("传递的参数为:" + a);

if (a > 10){
throw new MyException(a); // 抛出
}

System.out.println("OK");;
}

public static void main(String[] args) {
try {
test(11);
} catch (MyException e) {
throw new RuntimeException("MyException=>"+e);
}
}
}

实际应用中的经验总结:

  • 处理运行时异常时,采用逻辑去合理规避同时辅助try-catch处理
  • 在多重catch块后面,可以加一个catch(Exception) 来处理可能被遗漏的异常
  • 对于不确定的代码,也可以加上try-catch,处理潜在异常
  • 尽量去处理异常,切忌只是简单地调用printStackTrace()去打印输出
  • 具体如何处理异常,要根据不同的业务需求和异常类型去决定
  • 尽量添加finally语句块去释放占用的资源
  • Title: 异常(Exception)
  • Author: 茴香豆
  • Created at : 2024-06-05 14:51:43
  • Updated at : 2024-06-05 16:19:59
  • Link: https://hxiangdou.github.io/2024/06/05/Java-6/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments