异常发生后,Java 程序可以恢复执行吗?

java 8object oriented programmingprogramming

异常是指程序执行过程中出现的问题(运行时错误)。异常发生时,程序会突然终止,并且产生异常的代码行之后的代码将永远不会被执行。

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) {
      //创建一个大小为 5 的整数数组
      int inpuArray[] = new int[5];
      //填充数组
      inpuArray[0] = 41;
      inpuArray[1] = 98;
      inpuArray[2] = 43;
      inpuArray[3] = 26;
      inpuArray[4] = 79;
      //访问大于数组大小的索引
      System.out.println( inpuArray[3]);
   }
}

输出

26

相关文章