运行时异常可通过try-catch捕获并处理,提升程序健壮性;可使用多个catch块区分异常类型,finally或try-with-resources管理资源释放,确保关键路径稳定。

Java中的运行时异常(RuntimeException)是程序在运行过程中可能出现的错误,比如空指针、数组越界等。虽然这些异常可以不强制捕获,但合理地捕获和处理它们有助于提升程序的健壮性和可维护性。
使用try-catch捕获运行时异常
通过try-catch语句块,可以在可能出错的代码段周围进行包裹,一旦发生运行时异常,程序不会立即崩溃,而是跳转到catch块中处理。
- 将可能存在风险的代码放入try块中
- 用catch捕获具体的RuntimeException类型或其父类Exception
- 根据业务需要记录日志、提示用户或进行恢复操作
示例:
try {
String str = null;
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("发生了空指针异常:" + e.getMessage());
}
捕获多种运行时异常
一个try块可能引发不同类型的异常,可以使用多个catch块分别处理,提高错误处理的精确度。
立即学习“Java免费学习笔记(深入)”;
示例:
try {
int[] arr = new int[5];
System.out.println(arr[10]); // 数组越界
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组索引越界:" + e.getMessage());
} catch (RuntimeException e) {
System.out.println("其他运行时异常:" + e.getMessage());
}
使用finally释放资源
无论是否发生异常,finally块中的代码都会执行,适合用于关闭文件、数据库连接等资源清理工作。
示例:
FileInputStream fis = null;
try {
fis = new FileInputStream("test.txt");
// 读取文件内容
} catch (FileNotFoundException e) {
System.out.println("文件未找到:" + e.getMessage());
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用try-with-resources简化资源管理
对于实现了AutoCloseable接口的资源,推荐使用try-with-resources语法,自动管理资源关闭,避免遗漏。
示例:
try (FileInputStream fis = new FileInputStream("test.txt")) {
int data;
while ((data = fis.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
System.out.println("IO异常:" + e.getMessage());
}
基本上就这些。关键是理解运行时异常虽不要求强制捕获,但在关键路径上主动处理能显著提升程序稳定性。结合日志记录和资源管理,可以让异常处理更完整。










