最终在Java编程中尝试流控制。

例外是程序执行期间发生的问题(运行时错误)。一些异常是在编译时提示的,这些异常在编译时异常或检查的异常中是已知的。

如果发生异常,则程序会在导致异常的行突然终止,从而使程序的其余部分不执行。为防止这种情况,您需要处理异常。

尝试,抓到,最后阻止

为了处理异常,Java提供了try-catch块机制。

try块-将try块放置在可能生成异常的代码周围。try / catch块中的代码称为受保护代码。

语法

try {
   // Protected code
}
 catch (ExceptionName e1) {
   // Catch block
}

catch块-catch块涉及声明您要捕获的异常类型。如果try块中发生异常,则检查try之后的catch块。如果在catch块中列出了发生的异常类型,则将异常传递到catch块的方式与将参数传递给方法参数的方式一样。

最终块-最终块在try块或catch块之后。无论是否发生异常,始终都会执行一个finally代码块。

异常中的流控制

在异常处理中,可以具有try-catch,try-finally和try-catch-finally块。在这些情况下,您可能会遇到以下情况-

如果没有发生异常-如果try块中没有引发异常,则catch块中的代码(在try-catch或try-catch-finally中)将不会执行。无论如何,总是执行finally块(最终尝试或最终尝试捕获)

如果在try-catch中发生异常-当在try块内引发异常时, JVM终止了异常详细信息,而不是终止程序,将异常详细信息存储在异常堆栈中并进入catch块。

如果在catch块中列出/处理了发生的异常类型,则将异常传递给catch块的方式与将参数传递给方法参数的方式相同,并执行(相应)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

如果发生的异常未在catch块中处理,则使用throws关键字引发。最后一块中的代码被执行,并且异常在运行时发生。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Test {
   public static void main(String args[]) throws FileNotFoundException{
      System.out.println("Hello");
      try{
         File file =new File("my_file");
         FileInputStream fis = new FileInputStream(file);
      }
      catch(ArrayIndexOutOfBoundsException e){
      }
      finally{
         System.out.println("finally block");
      }
   }
}

输出结果

运行时异常

Hello
finally block
Exception in thread "main" java.io.FileNotFoundException: my_file (The system cannot find the file specified)
   at java.io.FileInputStream.open0(Native Method)
   at java.io.FileInputStream.open(Unknown Source)
   at java.io.FileInputStream.<init>(Unknown Source)
   at sample.Test.main(Test.java:12)

在try-catch-finally中发生异常

finally块位于try块或catch块之后。无论是否发生异常,始终都会执行一个finally代码块。

因此,如果try-catch-finally块中发生异常。catch块以及finally块中的代码都将执行。

public class ExcepTest {
   public static void main(String args[]) {
      int a[] = new int[2];
      try {
         System.out.println("Access element three :" + a[3]);
      }
      catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception thrown :" + e);
      }
      finally {
         a[0] = 6;
         System.out.println("First element value: " + a[0]);
         System.out.println("The finally statement is executed");
      }
   }
}

输出结果

Exception thrown : java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed