Java 中,异常(Exception) 是指程序在运行过程中发生的错误或意外情况。异常机制提供了一种优雅的方式来处理这些错误,避免程序崩溃。


1. 异常的分类

Java 中的异常分为两大类:

(1) Checked Exception(受检异常)

  • 编译期异常,必须处理,否则代码无法编译。
  • 例如:IOExceptionSQLExceptionFileNotFoundException 等。
  • 需要用 try-catchthrows 处理。

(2) Unchecked Exception(非受检异常)

  • 运行时异常,在程序运行时抛出。
  • 例如:NullPointerExceptionArrayIndexOutOfBoundsException 等。
  • 可以不强制处理,但建议通过代码逻辑避免。

2. 异常的基本语法

(1) 使用 try-catch 处理异常

1
2
3
4
5
6
7
8
9
10
11
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0; // 会抛出异常
} catch (ArithmeticException e) {
System.out.println("捕获异常: " + e.getMessage());
} finally {
System.out.println("执行 finally 语句,无论是否异常都会执行");
}
}
}

说明:

  • try:放置可能发生异常的代码。
  • catch:捕获异常并处理。
  • finally:可选,通常用于释放资源。

(2) 使用 throws 声明异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
public static void readFile(String filePath) throws FileNotFoundException {
Scanner scanner = new Scanner(new File(filePath));
}

public static void main(String[] args) {
try {
readFile("test.txt");
} catch (FileNotFoundException e) {
System.out.println("文件未找到: " + e.getMessage());
}
}
}

说明:

  • throws 用于声明可能抛出的异常。
  • 调用方法时,需要使用 try-catch 处理异常。

3. 多异常捕获

当可能抛出多种异常时,可以使用多 catch 语句:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Main {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // 数组越界异常
} catch (ArithmeticException e) {
System.out.println("算术异常: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界异常: " + e.getMessage());
} catch (Exception e) {
System.out.println("其他异常: " + e.getMessage());
}
}
}

说明:

  • 异常应从具体异常父类异常依次捕获,避免父类异常拦截所有异常。
  • Exception 是所有异常的父类。

4. 自定义异常

你可以通过继承 ExceptionRuntimeException 来创建自定义异常。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 自定义异常类
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}

public class Main {
public static void checkNumber(int number) throws CustomException {
if (number < 0) {
throw new CustomException("数字不能为负数: " + number);
}
System.out.println("数字是: " + number);
}

public static void main(String[] args) {
try {
checkNumber(-5);
} catch (CustomException e) {
System.out.println("捕获异常: " + e.getMessage());
}
}
}

说明:

  • 自定义异常通常用于业务逻辑层中进行异常处理。
  • 使用 throw 关键字主动抛出异常。

5. 常见异常类型

异常类型 描述
NullPointerException 访问空对象的属性或方法
ArrayIndexOutOfBoundsException 数组索引越界
ArithmeticException 算术运算异常,如除以 0
NumberFormatException 字符串转数字失败
IOException 输入输出异常
FileNotFoundException 文件未找到异常
ClassNotFoundException 找不到指定的类

总结

  • 使用 try-catch 捕获异常,避免程序崩溃。
  • 使用 finally 释放资源。
  • 使用 throws 声明异常,让调用者处理。
  • 自定义异常可用于业务逻辑校验。
  • 合理处理异常,有助于提高程序的健壮性和可维护性。