Java异常处理与捕获机制实例展示
在Java中,异常处理和捕获是通过try-catch-finally语句实现的。下面是一个简单的实例:
public class ExceptionHandlingExample {
public static void main(String[] args) {
// 假设我们正在读取一个文件
try {
FileReader fileReader = new FileReader("non_existent_file.txt");
// 这里会抛出FileNotFoundException,因为文件不存在
int content = fileReader.read();
System.out.println("Content: " + content);
} catch (FileNotFoundException e) {
// 处理文件未找到的异常
System.out.println("File not found error: " + e.getMessage());
} finally {
// 无论是否发生异常,finally块中的代码都会执行
System.out.println("This is always executed, no matter the exception.");
}
}
}
在这个例子中,我们尝试打开一个不存在的文件。这会引发FileNotFoundException
。通过try-catch语句,我们可以捕获并处理这个异常。最后无论是否发生异常,finally块中的代码都会执行。
还没有评论,来说两句吧...