在Java中,异常处理是一种用于处理程序运行时可能出现错误的情况的机制。Java异常按照其必须处理的要求可分为两类:检查异常(Checked Exception)和非检查异常(Unchecked Exception)。
检查异常(Checked Exception):
- 在编译期间就要求程序员处理的异常,如果不处理或捕获,编译器会报错。
- 示例:
import java.io.FileReader;
import java.io.IOException;
public class CheckedExample {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("non_existent_file.txt");
} catch (IOException e) {
// 处理IO异常,如文件未找到
e.printStackTrace();
}
}
}
在这个例子中,FileReader构造函数在打开不存在的文件时会抛出IOException,这是一个检查异常,因此必须在try-catch块中捕获或在方法签名中使用throws声明。
非检查异常(Unchecked Exception):
- 不要求在编译时必须处理的异常,也称为运行时异常,比如继承自
RuntimeException的异常。 - 示例:
public class UncheckedExample {
public static void main(String[] args) {
int[] array = new int[5];
try {
System.out.println(array[10]);
} catch (ArrayIndexOutOfBoundsException e) {
// 尽管这不是编译期要求,但仍然可以捕获并处理这个运行时异常
e.printStackTrace();
}
}
}
在这个例子中,尝试访问数组越界的位置会抛出ArrayIndexOutOfBoundsException,这是一个非检查异常,虽然编译器不会强制要求处理,但在运行时仍可能发生,一般推荐进行捕获处理以提升代码健壮性。
除了捕获异常,还可以自定义异常类并通过throw关键字抛出自定义的异常:
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class ExceptionHandlingExample {
public void doSomethingDangerous(int value) throws CustomException {
if (value < 0) {
throw new CustomException("Invalid negative value");
}
// 正常处理代码
}
public static void main(String[] args) {
ExceptionHandlingExample example = new ExceptionHandlingExample();
try {
example.doSomethingDangerous(-5);
} catch (CustomException e) {
e.printStackTrace();
}
}
}
在这个例子中,我们创建了一个自定义异常CustomException并在doSomethingDangerous方法中根据条件抛出。在main方法中,调用该方法并捕获这个自定义异常。

本文详细介绍了Java中的异常处理机制,包括检查异常(如IOException)和非检查异常(如ArrayIndexOutOfBoundsException),以及如何在编译时处理和自定义异常。

被折叠的 条评论
为什么被折叠?



