Java异常类可以分为两大类:检查异常和非检查异常。
检查异常是指在程序中可能会出现的异常,需要在代码中进行捕捉和处理。非检查异常是指运行期才会出现的异常,不需要强制捕捉处理。
Java异常类及其继承关系如下图所示:

一、常见异常类
1. NullPointerException
当一个应用程序试图在需要对象的地方使用 null 时,将引发该异常。
public class NullPointer {
public static void main(String[] args) {
String str = null;
System.out.println(str.length());
}
}
2. ArrayIndexOutOfBoundsException
当一个应用程序试图访问数组的索引超出范围时,将引发该异常。
public class ArrayIndex {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
System.out.println(arr[3]);
}
}
3. ClassCastException
当一个应用程序试图将一个对象强制转换为不是该对象当前类或其子类的类型时,将引发该异常。
public class ClassCast {
public static void main(String[] args) {
Object obj = "Hello";
Integer num = (Integer) obj;
}
}
4. ArithmeticException
当一个应用程序试图执行算术运算,而这个运算的第二个操作数为零时,将引发该异常。
public class Arithmetic {
public static void main(String[] args) {
int a = 10, b = 0;
int c = a / b;
}
}
二、捕获异常
Java提供了 try-catch 块来捕获异常。try 块中包含可能会出现异常的代码,一旦发生异常,catch 块中的代码将会被执行。
1. 单个异常
public class TryCatch {
public static void main(String[] args) {
int num1 = 10, num2 = 0;
try {
int result = num1 / num2;
System.out.println("结果是:" + result);
} catch (ArithmeticException e) {
System.out.println("除数不能为零");
}
System.out.println("程序结束");
}
}
2. 多个异常
public class TryCatch {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
try {
arr[3] = 4;
Object obj = "Hello";
Integer num = (Integer) obj;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界");
} catch (ClassCastException e) {
System.out.println("类型转换异常");
}
System.out.println("程序结束");
}
}
三、抛出异常
在程序中,如果出现了无法处理的异常,可以使用 throw 关键字将异常抛出,在调用该方法的地方使用 try-catch 块捕获异常。
1. 抛出检查异常
public class ThrowCheck {
public static void main(String[] args) throws FileNotFoundException {
FileReader reader = new FileReader("file.txt");
}
}
2. 抛出非检查异常
public class ThrowUncheck {
public static void main(String[] args) {
int num1 = 10, num2 = 0;
if (num2 == 0) {
throw new ArithmeticException("除数不能为零");
}
int result = num1 / num2;
System.out.println("结果是:" + result);
}
}
四、总结
Java异常处理机制可以帮助我们在程序出现异常时及时处理,避免程序崩溃。在编写程序时,应该尽可能考虑到可能出现的异常,并进行捕获和处理,避免出现异常后无法恢复的情况。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/286181.html