Java 异常处理试题及答案:常见异常场景、处理机制考点全梳理

一、核心异常处理机制

Java 异常处理基于 try-catch-finally 结构:

try {
    FileInputStream fis = new FileInputStream("test.txt");
    int data = fis.read();
} 
catch (FileNotFoundException e) {
    System.err.println("文件未找到: " + e.getMessage());
} 
catch (IOException e) {
    System.err.println("IO异常: " + e.getCause());
} 
finally {
    System.out.println("资源清理操作");
}

考点提示finally 块始终执行,常用于资源释放


二、5大高频异常场景解析

  1. 空指针异常
String str = null;
System.out.println(str.length()); // NullPointerException

避坑方案

  • 使用 Objects.requireNonNull()
  • 启用 -XX:+ShowCodeDetailsInExceptionMessages
  1. 数组越界异常
int[] arr = new int[3];
System.out.println(arr[5]); // ArrayIndexOutOfBoundsException

防御方案
if(index >= 0 && index < arr.length)

  1. 类型转换异常
Object obj = "Java";
Integer num = (Integer) obj; // ClassCastException

解决方案
使用 instanceof 预判断:
if(obj instanceof Integer)


三、异常处理进阶考点

  1. 异常传播机制
void methodA() throws IOException {
    throw new IOException("级联异常");
}

void methodB() {
    try {
        methodA();
    } catch (IOException e) {
        throw new RuntimeException("封装异常", e);
    }
}

面试重点:异常链的 initCause() 方法应用

  1. 自定义异常实现
class BalanceException extends Exception {
    public BalanceException(String message) {
        super(message);
    }
}

void withdraw(double amount) throws BalanceException {
    if(amount > balance) 
        throw new BalanceException("余额不足");
}


四、异常处理原则

  1. 精准捕获原则
    ❌ 避免 catch(Exception e)
    ✅ 明确异常类型:catch(FileNotFoundException | SQLException e)

  2. 资源关闭规范

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    // 自动关闭资源
}

新版特性:JDK9 支持 final 资源注入


五、实战试题精析

试题:以下代码输出什么?

public static void main(String[] args) {
    try {
        System.out.println("try 返回值: " + test());
    } catch (Exception e) {
        System.out.println("catch 捕获: " + e.getMessage());
    }
}

static String test() throws Exception {
    try {
        throw new Exception("方法内异常");
    } finally {
        return "finally 返回值";
    }
}

答案

try 返回值: finally 返回值

考点解析:finally 块中的 return 会覆盖 try 块中的异常


附:异常处理性能优化

  1. 避免在循环内捕获异常
  2. 使用预检查替代异常捕获:
// 错误示范
try {
    obj.method();
} catch (NullPointerException e) { ... }

// 正确方案
if(obj != null) {
    obj.method();
}

数据统计:异常实例化比普通对象创建慢 100 倍(JVM 需填充堆栈轨迹)

掌握异常处理机制是 Java 开发的核心能力,理解异常传播原理、熟悉常见异常场景、遵循最佳实践原则,方能在实际开发与面试中游刃有余。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐