模块 5 · 第 1 课(共 2)课程中的9/14~12 min
模块课程(1/2)
Try-Catch 块
在 Java 中,运行时错误是使用 异常 来处理的。异常处理允许我们拦截异常情况并防止程序崩溃。
try-catch 结构
为了处理潜在的异常,我们将有风险的代码包含在 try 块中。如果 try 块内发生错误,JVM 将停止执行它并搜索匹配的 catch 块来处理异常。
Java
try {
int result = 10 / 0; // Generates ArithmeticException
System.out.println("This will not be printed");
} catch (ArithmeticException e) {
System.out.println("Arithmetic error occurred: " + e.getMessage());
}finally 块
finally 块是可选的,并且始终执行,无论是否引发异常。它非常适合释放资源或执行清理操作。
Java
try {
System.out.println("Executing logic");
} catch (Exception e) {
System.out.println("Error");
} finally {
System.out.println("This block is always executed");
}抛出异常:throw
我们可以使用 throw 关键字有意抛出异常,后跟异常类的新实例。
Java
public static void checkScore(int score) {
if (score < 0 || score > 100) {
throw new IllegalArgumentException("Score must be between 0 and 100");
}
}自己尝试一下
锻炼#java.m5.l1.e1
尝试:0加载中...
通过插入一个 try-catch 块来处理由 a / b 除法产生的潜在 ArithmeticException 来完成代码。如果出现错误,请打印“错误:除以零”。
正在加载编辑器...
显示提示
将除法运算插入“try”块中并捕获“ArithmeticException”,打印所需的消息。
3 次尝试后可用的解决方案
锻炼#java.m5.l1.e2
尝试:0加载中...
完成代码以实现 try-catch-finally 块。在 try 块中,尝试使用 Integer.parseInt 将字符串 str 转换为整数。在 catch 块中,拦截 NumberFormatException 并打印“无效数字”。在finally 块中,打印“Finally”。
正在加载编辑器...
显示提示
编写 `try { ... } catch (NumberFormatException e) { ... } finally { ... }` 块结构。
3 次尝试后可用的解决方案
锻炼#java.m5.l1.e3
尝试:0加载中...
如果提供的年龄小于 18 岁,则通过抛出带有消息“Underage”的 IllegalArgumentException 来完成 checkAge 方法。
正在加载编辑器...
显示提示
使用 if (age < 18) 和 throw new 关键字来实例化并抛出异常。
3 次尝试后可用的解决方案