java退出程序异常分类
一、概述
在 Java 中,退出程序异常主要分为 Error 和 Exception 两大类,它们各自包含多种具体类型,以下是详细介绍及具体影响实例:
二、分类
Error(错误)
- 描述:Error 表示系统级的错误,是 Java 运行时环境内部的错误或资源耗尽等严重问题,通常是不可恢复的,一般不应该由应用程序来处理。
- 常见类型及实例
- OutOfMemoryError:当 Java 虚拟机无法为新的对象分配足够的内存空间时抛出。例如,以下代码尝试创建一个非常大的数组,可能会导致 OutOfMemoryError。
public class OutOfMemoryErrorExample {
public static void main(String[] args) {
int[] array = new int[Integer.MAX_VALUE];
}
}
- StackOverflowError:当线程的栈空间被耗尽时抛出,通常是因为方法调用层次过深,例如无限递归。如下代码:
public class StackOverflowErrorExample {
public static void main(String[] args) {
recursiveMethod();
}
public static void recursiveMethod() {
recursiveMethod();
}
}
Exception(异常)
- 描述:Exception 表示程序运行过程中出现的可恢复的异常情况,可以通过 try - catch 语句进行捕获和处理,使程序能够继续执行。
- 常见类型及实例
- IOException:在进行输入输出操作时发生错误会抛出此异常。例如,试图读取一个不存在的文件时:
import java.io.FileInputStream;
import java.io.IOException;
public class IOExceptionExample {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("non_existent_file.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}
- NullPointerException:当应用程序试图在一个空对象上调用方法或访问属性时抛出。例如:
public class NullPointerExceptionExample {
public static void main(String[] args) {
String str = null;
System.out.println(str.length());
}
}
- ArrayIndexOutOfBoundsException:当访问数组时使用了超出数组范围的索引会抛出该异常。例如:
public class ArrayIndexOutOfBoundsExceptionExample {
public static void main(String[] args) {
int[] array = {1, 2, 3};
System.out.println(array[3]);
}
}
- ClassCastException:当试图将一个对象强制转换为不兼容的类型时抛出。例如:
public class ClassCastExceptionExample {
public static void main(String[] args) {
Object obj = new Integer(1);
String str = (String) obj;
}
}
- NumberFormatException:当试图将一个字符串转换为数字格式,但字符串的格式不正确时抛出。例如:
public class NumberFormatExceptionExample {
public static void main(String[] args) {
String str = "abc";
int num = Integer.parseInt(str);
}
}