背景
本文是《Java 后端从小白到大神》修仙系列第十二篇
,正式进入Java后端
世界,本篇文章主要聊Java基础
。若想详细学习请点击首篇博文,我们开始把。
文章概览
- 异常处理
异常处理
1. try-catch 块
用于捕获并处理代码块中的异常。
1
2
3
4
5
|
try {
int result = 10 / 0; // 抛出 ArithmeticException
} catch (ArithmeticException e) {
System.out.println("错误:除数不能为零!");
}
|
2. 多个 catch 块
处理不同类型的异常,子类异常需在前。
1
2
3
4
5
6
7
8
|
try {
int[] arr = new int[5];
arr[10] = 50; // 抛出 ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界!");
} catch (Exception e) {
System.out.println("其他异常:" + e.getMessage());
}
|
3. finally 块
无论是否发生异常,都会执行的代码块(常用于资源清理)。
1
2
3
4
5
6
7
|
try {
FileInputStream file = new FileInputStream("test.txt");
} catch (FileNotFoundException e) {
System.out.println("文件未找到!");
} finally {
System.out.println("无论是否异常,都会执行。");
}
|
4. throw 关键字
主动抛出异常(需在方法内处理或声明)。
1
2
3
4
5
|
void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("年龄未满18岁!");
}
}
|
5. throws 关键字
声明方法可能抛出的异常(由调用者处理)。
1
2
3
4
|
// 方法声明可能抛出 IOException
public void readFile() throws IOException {
FileReader file = new FileReader("test.txt");
}
|
6. try-with-resources(Java 7+)
自动关闭资源(资源需实现 AutoCloseable
接口)。
1
2
3
4
5
6
|
try (FileInputStream fis = new FileInputStream("test.txt")) {
int data = fis.read();
} catch (IOException e) {
System.out.println("IO异常:" + e.getMessage());
}
// 无需显式关闭,资源自动关闭
|
7. 自定义异常
创建继承自 Exception
或 RuntimeException
的类。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
// 自定义异常类
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
// 使用示例
void validate(int value) throws MyException {
if (value < 0) {
throw new MyException("值不能为负数!");
}
}
// 调用时捕获
try {
validate(-5);
} catch (MyException e) {
System.out.println(e.getMessage());
}
|
8. 异常分类
- 检查型异常(Checked):编译时检查,必须处理(如
IOException
)。
- 非检查型异常(Unchecked):运行时异常(如
NullPointerException
)。
总结
上述常用异常处理方式,需要掌握。