finally 块
本课属于 Coddy Java 学习旅程的“逻辑与流程”单元。第 41 课,共 59 课。
finally 块中的代码会在 try-catch 块之后执行,无论是否发生异常。它通常用于清理操作,例如关闭文件或数据库连接。
这是 try-catch-finally 块的基本结构:
try {
// 可能抛出异常的代码
} catch (ExceptionType e) {
// 处理异常的代码
} finally {
// 始终会执行的代码
}来看一个计数器的示例:
int counter = 0;
try {
int result = 10 / 0;
// 这里会抛出异常
counter = 1;
} catch (ArithmeticException e) {
counter = 2;
} finally {
counter = 3;
// 这里的代码总会执行
}执行上述代码后,counter 中包含:
3
catch 括号中的类型决定了这个代码块会处理哪些错误。常见的有两种:整数除以零时会抛出 ArithmeticException,以及文本不是数字时,Integer.parseInt() 会抛出 NumberFormatException。一个 catch 可以同时处理多种类型:
try {
int value = Integer.parseInt(text);
int result = 10 / value;
} catch (ArithmeticException | NumberFormatException e) {
// 处理这两种异常
} finally {
// 始终会运行
}改为捕获 Exception 的范围更广:它会处理这两种异常以及其他任何异常。
挑战
简单创建一个名为 processNumber 的方法,它接受两个参数:
- 一个用于转换为整数的字符串(
number) - 一个布尔值(
shouldThrow),用于决定是否抛出异常
该方法应:
- 将结果变量初始化为 0
- 在 try 块中:
- 如果 shouldThrow 为 true,则用 10 除以 0
- 否则,将 number 字符串转换为整数,并将其存储在 result 中
- 在 catch 块中:将 result 设为 -1
- 在 finally 块中:给 result 加上 100
- 以字符串形式返回 result
亲手试试
import java.util.Scanner;
public class Main {
public static String processNumber(String number, boolean shouldThrow) {
// 在这里编写你的代码
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String number = scanner.nextLine();
boolean shouldThrow = Boolean.parseBoolean(scanner.nextLine());
System.out.println(processNumber(number, shouldThrow));
}
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
逻辑与流程中的所有课
自己练习: Java 在线编译器