课程进度 55% · 第6/10章第6/10章 · 标签 1/2
— 1 —
try-catch-finally
异常处理是 Java 程序健壮性的重要保障。通过 try-catch 机制,程序可以从异常状态中恢复并继续执行。
java
1
try {
2
int result = 10 / 0; // 抛出异常
3
System.out.println("不会执行");
4
} catch (ArithmeticException e) {
5
System.out.println("除数不能为零");
6
System.out.println(e.getMessage());
7
} catch (Exception e) {
8
System.out.println("其他错误: " + e);
9
} finally {
10
System.out.println("总是执行");
11
}
12
13
// try-with-resources(自动关闭资源)
14
try (BufferedReader br = new BufferedReader(
15
new FileReader("file.txt"))) {
16
System.out.println(br.readLine());
17
} catch (IOException e) {
18
e.printStackTrace();
19
}
— 2 —
异常类型
java
1
// 检查型异常(必须处理)
2
try {
3
Thread.sleep(1000);
4
} catch (InterruptedException e) {
5
Thread.currentThread().interrupt();
6
}
7
8
// 非检查型异常(可选处理)
9
int[] arr = new int[5];
10
arr[10] = 1; // ArrayIndexOutOfBoundsException
11
12
// 抛出异常
13
public void withdraw(double amount) {
14
if (amount > balance) {
15
throw new IllegalArgumentException(
16
"余额不足");
17
}
18
balance -= amount;
19
}
20
21
// throws 声明
22
public void readFile() throws IOException {
23
Files.readString(Path.of("test.txt"));
24
}