合理的异常处理是构建健壮应用的关键。
Java异常分为两类:
需要显式处理:
public void readFile(String path) throws IOException { Files.readAllLines(Paths.get(path)); }
无需显式处理:
public int divide(int a, int b) { return a / b; // 可能抛出ArithmeticException }
try { // 可能抛出异常的代码 } catch (IOException e) { // 处理异常 } finally { // 总是执行的代码 }
自动关闭资源:
try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } // 自动关闭
public void setAge(int age) { if (age < 0) { throw new IllegalArgumentException("年龄不能为负"); } this.age = age; }
public void save() throws SQLException { // 可能抛出SQLException }
public class BusinessException extends RuntimeException { private String code; public BusinessException(String code, String message) { super(message); this.code = code; } }
异常处理不仅是为了程序不崩溃,更是为了提供清晰的错误信息。