10分钟学会Java异常处理,快速掌握try-catch与自定义异常
本文面向Java初学者,系统讲解Java异常捕获与处理的基础知识及实用技巧。内容涵盖异常分类、try-catch-finally语句、抛出异常、链式异常处理、自定义异常以及最佳实践。通过实例讲解和分步操作,帮助读者快速掌握Java异常处理技能,提高程序的健壮性和可维护性。
正文教程
一、Java异常基础
异常分类
Checked异常(受检查异常):编译期必须处理,如
IOExceptionUnchecked异常(运行期异常):编译器不强制处理,如
NullPointerException
二、try-catch捕获异常
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0; // 会抛出ArithmeticException
} catch (ArithmeticException e) {
System.out.println("捕获异常: " + e);
}
}
}
技巧:try中放可能出错的代码,catch捕获特定异常类型
三、finally语句
try {
int[] arr = new int[3];
System.out.println(arr[5]); // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界异常");
} finally {
System.out.println("无论是否异常,都会执行");
}
技巧:finally常用于释放资源,如文件、数据库连接
四、抛出异常(throw)
public void checkAge(int age) throws IllegalArgumentException {
if(age < 18) {
throw new IllegalArgumentException("年龄必须大于等于18");
}
}
技巧:
throw用于主动抛出异常,throws声明方法可能抛出的异常
五、多重异常捕获
try {
int[] arr = new int[3];
arr[5] = 10;
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println("捕获多种异常: " + e);
}
技巧:Java 7+支持多异常捕获,减少重复catch
六、自定义异常
class MyException extends Exception {
public MyException(String message) { super(message); }
}
public class Test {
public static void main(String[] args) {
try {
throw new MyException("自定义异常发生");
} catch (MyException e) {
System.out.println(e.getMessage());
}
}
}
技巧:自定义异常可用于特定业务场景,提高代码可读性
七、异常链(Exception Chaining)
try {
try {
int a = 10/0;
} catch (ArithmeticException e) {
throw new RuntimeException("包装异常", e);
}
} catch (RuntimeException e) {
e.printStackTrace();
}
技巧:异常链可保留原始异常信息,便于调试
八、实用技巧总结
优先捕获最具体的异常类型
finally用于资源释放
throw和throws用于异常抛出和声明
自定义异常提升代码可读性和业务表达能力
异常链有助于调试复杂问题