Java异常处理:优雅地处理错误
Java异常处理:优雅地处理错误
概述
异常处理是Java程序健壮性的重要保障。Java提供了完善的异常处理机制,可以捕获和处理运行时错误,避免程序崩溃。
1. 异常体系结构
// 异常层次结构
// Throwable
// ├── Error(系统错误,无法处理)
// │ ├── OutOfMemoryError
// │ └── StackOverflowError
// └── Exception(程序异常,可以处理)
// ├── RuntimeException(非受检异常)
// │ ├── NullPointerException
// │ ├── ArrayIndexOutOfBoundsException
// │ └── IllegalArgumentException
// └── 受检异常
// ├── IOException
// ├── SQLException
// └── ClassNotFoundException
2. try-catch-finally
public class ExceptionDemo {
public static void main(String[] args) {
try {
int result = divide(10, 0);
System.out.println("结果: " + result);
} catch (ArithmeticException e) {
System.out.println("算术错误: " + e.getMessage());
} catch (Exception e) {
System.out.println("其他错误: " + e.getMessage());
} finally {
System.out.println("finally块始终执行");
}
}
public static int divide(int a, int b) {
return a / b;
}
}
3. throws与throw
public class FileService {
public String readFile(String path) throws IOException {
if (path == null) {
throw new IllegalArgumentException("文件路径不能为空");
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(path));
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
return content.toString();
} finally {
if (reader != null) {
reader.close();
}
}
}
}
4. 自定义异常
public class BusinessException extends RuntimeException {
private String code;
private String message;
public BusinessException(String code, String message) {
super(message);
this.code = code;
this.message = message;
}
public String getCode() {
return code;
}
}
public class UserService {
public void register(String username, String password) {
if (username == null || username.length() < 3) {
throw new BusinessException("USER_001", "用户名至少3个字符");
}
if (password == null || password.length() < 6) {
throw new BusinessException("USER_002", "密码至少6个字符");
}
}
}
5. try-with-resources
public class DatabaseConnection implements AutoCloseable {
public DatabaseConnection() {
System.out.println("打开数据库连接");
}
public void query(String sql) {
System.out.println("执行查询: " + sql);
}
@Override
public void close() {
System.out.println("关闭数据库连接");
}
}
public class ResourceDemo {
public static void main(String[] args) {
try (DatabaseConnection conn = new DatabaseConnection()) {
conn.query("SELECT * FROM users");
}
// 自动调用close()方法
}
}
6. 异常处理最佳实践
public class ExceptionBestPractice {
// 捕获具体的异常类型
public void specificCatch() {
try {
// 业务逻辑
} catch (FileNotFoundException e) {
// 处理文件未找到
} catch (IOException e) {
// 处理其他IO异常
}
}
// 不要忽略异常
public void dontIgnore() {
try {
// 业务逻辑
} catch (Exception e) {
logger.error("发生错误", e);
throw new BusinessException("SYS_001", "系统错误");
}
}
}
最佳实践
- 捕获具体异常:不要捕获Exception或Throwable
- 不要忽略异常:至少记录日志
- 使用try-with-resources:自动管理资源
- 自定义有意义的异常:提供错误码和详细信息
- 避免过度使用异常:异常处理有性能开销
总结
异常处理是Java编程的重要组成部分,它保证了程序的健壮性。掌握异常处理机制,合理使用try-catch、自定义异常和资源管理,可以编写出更加稳定可靠的应用程序。