异常是 Java 中的一种对象,表示程序运行中遇到的或者可能遇到的错误,当程序遇到无法正常处理的情况时,Java会“抛”出一个异常对象来通知用户程序出现或可能出现了问题。(我是这么理解的)
一、异常的分类
Java中的异常一般分为两类:
1.Error
定义:系统级错误(如内存溢出),程序无法处理
常见类型:OutOfMemoryError,StackOverflowError。
处理方式:一般与我们开发者无关,无需捕获,通常由JVM来处理。
2.Exception
表示程序可以捕获和处理的异常情况,一般分为两类:
Checked Exception(受检异常)
必须处理(捕获或声明抛出)
常见类型:`IOException`, `SQLException`
Unchecked Exception(非受检异常)
无需强制处理
通常由程序逻辑错误引起,如`NullPointerException`、`ArrayIndexOutOfBoundsException` 等。
例如下面代码就是由数组越界引起的:
public class Exception1 {
public static void main(String[] args) {
int[] a = new int[5];
for (int i = 0; i < a.length; i++) {
a[i] = i;
}
System.out.println(a[5]);
}
}
运行结果会报错:
二、异常的处理
Java提供了多种异常处理机制,主要包括
1.try-catch 块
用于捕获和处理异常
try块中包含可能出现异常的代码块,catch块用于捕获并处理异常
try {
// 可能抛出异常的代码
int result = 10 / 0;
} catch (ArithmeticException e) {
// 处理异常
System.out.println("发生了除以零的异常: " + e.getMessage());
}
2.finally 块
一般当Java出现异常时会停止当前程序的运行,但是当出现finall块时,finall块中的代码会继续执行
无论是否捕获到异常,`finally` 块中的代码都会执行。
常用于清理资源,如关闭文件流、数据库连接等。
public class Exception1 {
public static void main(String[] args) {
try {
// 可能抛出异常的代码
int result = 10 / 0;
} catch (ArithmeticException e) {
// 处理异常
System.out.println("发生了除以零的异常: " + e.getMessage());
}finally {
// 清理资源
System.out.println("finally 块总是执行");
}
}
}
3.throw 关键字
用于手动抛出一个异常对象
public class Exception1 {
public static void main(String[] args) {
int a = 10;
int b = 0;
System.out.println(chu(a,b));
}
public static int chu(int a, int b) {
if (b <= 0) {
throw new IllegalArgumentException("除数不能为 0");
}
else
return a / b;
}
}
4.throws 关键字
在方法声明中使用,表示该方法可能会抛出某种异常,调用该方法时需要处理这些异常。
public class Exception1 {
public static void main(String[] args) {
int a = 10;
int b = 0;
try {
System.out.println(chu(a, b));
} catch (ArithmeticException e) {
System.err.println(e.getMessage());
}
}
public static int chu(int a, int b) {
if (b == 0) {
throw new ArithmeticException("除数不能为 0");
}
return a / b;
}
}
三、自定义异常
Java允许开发者自己定义异常类,自定义异常类通常要继承自Exception类或者其子类。
下面是自定义了一个除数不能为0的异常
public class Exception1 {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
System.out.println(chu(a, b));
} catch (MyException e) {
System.err.println("发生异常: " + e.getMessage());
}
}
public static int chu(int a, int b) throws MyException {
if (b == 0) {
throw new MyException("除数不能为0");
}
return a / b;
}
// 自定义异常类
public static class MyException extends Exception {
public MyException(String message) {
super(message);
}
public MyException(String message, Throwable cause) {
super(message, cause);
}
}
}
四、注意事项
- 不要忽略异常:空的catch块是危险的
- 具体异常优先:避免直接捕获
Exception - 使用finally关闭资源(或try-with-resources)
五、常见的异常类型表
| 异常类型 | 常见场景 |
|---|---|
NullPointerException | 调用null对象的方法或属性 |
ArrayIndexOutOfBoundsException | 数组越界访问 |
ClassCastException | 错误的类型转换 |
NumberFormatException | 字符串转换为数字失败 |
IllegalArgumentException | 方法接收到非法参数 |