Java 异常发生后是否可以恢复执行?
异常是在程序执行过程中发生的错误(运行时错误)。当发生异常时,程序会突然终止,并且异常行之后的代码将不会执行。
Java 中有两种类型的异常。
- 未检查异常 − 未检查异常是在执行时发生的异常。这些也称为运行时异常。这些包括编程错误,例如逻辑错误或 API 的不正确使用。运行时异常在编译时会被忽略。
- 已检查异常 − 已检查异常是在编译时发生的异常,这些也称为编译时异常。这些异常在编译时不能简单地被忽略;程序员应该注意(处理)这些异常。
恢复程序
当发生已检查/编译时异常时,您可以使用 try-catch 块来处理它以恢复程序。使用它们,您可以在程序执行完成后显示您自己的消息或显示异常消息。
示例
import java.io.File;
import java.io.FileInputStream;
public class Test {
public static void main(String args[]){
System.out.println("Hello");
try{
File file =new File("my_file");
FileInputStream fis = new FileInputStream(file);
}catch(Exception e){
System.out.println("Given file path is not found");
}
}
}输出
Given file path is not found
当发生运行时异常时,您可以处理运行时异常并避免异常终止,但是,Java 中没有针对运行时异常的特定修复方法,具体取决于异常类型,您需要更改代码。
示例
public class ExceptionExample {
public static void main(String[] args) {
//Creating an integer array with size 5
int inpuArray[] = new int[5];
//Populating the array
inpuArray[0] = 41;
inpuArray[1] = 98;
inpuArray[2] = 43;
inpuArray[3] = 26;
inpuArray[4] = 79;
//Accessing index greater than the size of the array
System.out.println( inpuArray[3]);
}
}输出
26
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP