7.1 异常与捕获
异常(exception)是程序运行过程中出现的非正常情况。异常不一定意味着程序必须崩溃;如果提前设计好处理方式,程序可以给出提示、记录问题,或者继续执行后续逻辑。
常见异常
常见异常包括:
NumberFormatException:文本不能转成数字,例如把"3.6"转成int。ArithmeticException:非法算术运算,例如整数除法中除数为 0。ArrayIndexOutOfBoundsException:数组下标(index)越界。NullPointerException:通过null引用访问字段或方法。FileNotFoundException:打开不存在的文件。IllegalArgumentException:方法收到了不合理的参数。
注意
异常不是用来代替普通条件判断的。能用
if 提前判断的简单规则,通常仍然应该先用 if;异常更适合处理“运行时才知道是否会失败”的情况。正在加载概念检查...
try、catch、finally
try 中放可能出错的代码,catch 中放错误处理代码,finally 中放无论是否出错都要执行的收尾代码。
正在加载交互实验...
java
import java.util.Scanner;
public class DivisionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try {
System.out.print("请输入被除数:");
int dividend = Integer.parseInt(input.nextLine());
System.out.print("请输入除数:");
int divisor = Integer.parseInt(input.nextLine());
int quotient = dividend / divisor;
System.out.printf("%d / %d = %d%n", dividend, divisor, quotient);
} catch (NumberFormatException error) {
System.out.println("只支持输入整数。");
} catch (ArithmeticException error) {
System.out.println("除数不能为 0。");
} finally {
System.out.println("本次计算结束。");
}
}
}一次可能的运行结果:
text
请输入被除数:21
请输入除数:4
21 / 4 = 5
本次计算结束。Java 没有 Python 那样的 try-else。没有异常时才需要执行的代码,通常放在 try 中风险语句之后。整体流程仍然很清楚:try 负责尝试,catch 负责失败,finally 负责收尾。
正在加载概念检查...
捕获具体异常
不要一开始就写过宽的 catch (Exception error)。如果什么异常都捕获,程序可能把真正的 bug 也吞掉,导致问题更难发现。
java
try {
int score = Integer.parseInt(input.nextLine());
} catch (NumberFormatException error) {
System.out.println("成绩必须是整数。");
}上面只捕获 NumberFormatException,因为这段代码真正预期的失败就是“输入不能转成整数”。
正在加载概念检查...
throw
throw 可以主动抛出异常。它适合表达“这个输入不满足方法要求”,让错误在正确的位置被发现,再交给调用者处理。
正在加载交互实验...
java
import java.util.Scanner;
public class ScoreDemo {
static double normalizeScore(int score) {
if (score < 0 || score > 100) {
throw new IllegalArgumentException("成绩必须在 0 到 100 之间。");
}
return score / 100.0;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try {
System.out.print("请输入成绩:");
int score = Integer.parseInt(input.nextLine());
double ratio = normalizeScore(score);
System.out.printf("成绩比例:%.2f%n", ratio);
} catch (NumberFormatException error) {
System.out.println("输入无效:成绩必须是整数。");
} catch (IllegalArgumentException error) {
System.out.println("输入无效:" + error.getMessage());
}
}
}一次可能的运行结果:
text
请输入成绩:120
输入无效:成绩必须在 0 到 100 之间。这里 normalizeScore() 不负责打印提示,它只负责保证自己的输入合法。外层调用者负责决定怎么提示用户。
正在加载概念检查...
正在加载本节练习...