一、异常的分类
-
Throwable
顶级异常类,java中所以的异常都继承于该类。它有Exception和Error两个子类。
-
Exception
Throwable类的子类,它通常是我们程序的异常,其中分为检查异常和RuntimeException(运行时异常)。
-
检查异常
检查异常是Exception的子类,它通常是在程序编译过程中编译工具所检查出的异常。
-
RuntimeException(运行时异常)
RuntimeException是Exception的子类,它通常是在我们编写完代码运行期间出现的异常,通常可以在控制台看到该类异常。
-
Error错误
该类异常通常我们无法进行人为修复。
-
思维导图
二、常见异常
RuntimeException(运行时异常)
1.NullPointerException(空指针异常)
-
描述:当应用程序试图在需要对象的地方使用
null
时,抛出该异常。 -
示例代码:
public class NullPointerExceptionExample {
public static void main(String[] args) {
String str = null;
// 由于str为null,抛出 NullPointerException
System.out.println(str.length());
}
}
-
运行结果:
2.ArithmeticException(算数异常)
-
描述:当出现异常的运算条件时,抛出该异常。
-
示例代码:
public class ArithmeticExceptionExample {
public static void main(String[] args) {
int a = 10;
int b = 0;
// 由于除数不能为零,会抛出 ArithmeticException
int n = a / b;
}
}
-
运行结果:
3.ArrayIndexOutOfBoundsException(数组下标约见)
-
描述:当使用的数组下标超出数组允许范围时,抛出该异常。
-
示例代码:
public class ArrayIndexOutOfBoundsExceptionExample {
public static void main(String[] args) {
int[] arr = new int[5];
// 数组长度为 5,有效下标是 0 到 4,而我们要那到下标为 5 的元素,抛出
//ArrayIndexOutOfBoundsException
System.out.println(arr[5]);
}
}
-
运行结果:
4.ClassCastException(类型转换异常)
-
描述:当试图将对象强制转换为不是实例的子类时,抛出该异常。
-
示例代码:
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
public class ClassCastExceptionExample {
public static void main(String[] args) {
Animal animal = new Dog();
// 由于 animal 实际是 Dog 类型,不能下转型为 Cat 类型,抛出ClassCastException异常
Cat cat = (Cat) animal;
}
}
-
运行结果:
5.NumberFormatException(字符格式转化异常)
-
描述:当应用程序试图将字符串转换成一种数值类型,但该字符串不能转换为适当格式时,抛出该异常。
-
示例代码:
public class NumberFormatExceptionExample {
public static void main(String[] args) {
String str = "abc";
// 由于 "abc" 不能转换为整数,抛出 NumberFormatException异常
int num = Integer.parseInt(str);
}
}
-
运行结果:
检查异常
1.
IOException
-
描述:表示输入输出操作中出现的异常。它是所有输入输出相关异常的父类,例如文件读写操作、网络通信等可能会抛出该异常。
2.SQLException
-
描述:表示与数据库交互时出现的异常,例如数据库连接失败、SQL 语句执行错误等。
错误Error
1.StackOverflowError(虚拟机栈溢出错误)
-
描述:当应用程序递归调用过深,导致栈空间耗尽时,抛出该错误。
-
示例代码:
public class StackOverflowErrorExample {
public static void recursiveMethod() {
recursiveMethod(); // 无限递归调用
}
public static void main(String[] args) {
recursiveMethod();
}
}
-
运行结果:
2.OutOfMemoryError(内存溢出错误)
-
描述:当 Java 虚拟机无法为对象分配足够的内存时,抛出该错误。通常是由于创建了大量对象,导致堆内存耗尽。
-
示例代码:
public class OutOfMemoryErrorExample {
public static void main(String[] args) {
List<byte[]> list = new ArrayList<>();
while (true) {
list.add(new byte[1024 * 1024]); // 不断创建 1MB 的字节数组
}
}
}
-
运行结果: