java异常如何处理
异常处理的基本概念
Java异常分为检查型异常(Checked Exception)和非检查型异常(Unchecked Exception)。检查型异常需在编译时处理(如IOException),非检查型异常包括运行时异常(如NullPointerException)和错误(如OutOfMemoryError)。
try-catch-finally 块
通过try捕获可能抛出异常的代码,catch处理特定异常,finally确保资源释放(无论是否发生异常):
try {
// 可能抛出异常的代码
FileInputStream file = new FileInputStream("test.txt");
} catch (FileNotFoundException e) {
// 处理文件未找到异常
System.err.println("文件未找到: " + e.getMessage());
} finally {
// 关闭资源
if (file != null) {
file.close();
}
}
多重 catch 块
按异常子类到父类的顺序捕获多个异常:
try {
int[] arr = {1, 2};
System.out.println(arr[3]); // 抛出ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("数组越界: " + e);
} catch (Exception e) {
System.err.println("通用异常处理: " + e);
}
throws 声明异常
在方法签名中使用throws将异常抛给调用者处理:
public void readFile() throws IOException {
FileReader reader = new FileReader("file.txt");
// 其他操作
}
throw 手动抛出异常
通过throw主动抛出异常对象:
if (input < 0) {
throw new IllegalArgumentException("输入不能为负数");
}
自定义异常
继承Exception或RuntimeException创建自定义异常:
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
// 使用示例
try {
throw new CustomException("自定义异常");
} catch (CustomException e) {
System.err.println(e.getMessage());
}
try-with-resources
自动管理资源(需实现AutoCloseable接口):
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("IO异常: " + e);
}
异常链与 cause
通过initCause()或构造方法传递原始异常:
try {
// 模拟原始异常
throw new NullPointerException("原始异常");
} catch (NullPointerException e) {
IllegalArgumentException ex = new IllegalArgumentException("包装异常");
ex.initCause(e);
throw ex;
}
最佳实践
- 精准捕获:避免直接捕获
Exception,优先处理具体异常类型。 - 资源释放:使用
try-with-resources或finally确保资源关闭。 - 日志记录:通过日志工具(如SLF4J)记录异常详情。
- 避免空捕获:
catch块中至少记录异常信息。 - 自定义异常:为业务逻辑定义清晰的异常类型。
示例日志记录:
catch (IOException e) {
logger.error("文件操作失败", e);
throw new BusinessException("业务处理失败", e);
}






