Java 编程中 try catch finally 中的流控制。

java 8object oriented programmingprogramming

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

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

Try、catch、finally 块

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

try 块 − try 块位于可能生成异常的代码周围。try/catch 块内的代码称为受保护代码。

语法

try {
   // 受保护的代码
}
 catch (ExceptionName e1) {
   // Catch 块
}

catch 块 − catch 块涉及声明您尝试捕获的异常类型。如果 try 块中发生异常,则会检查 try 后面的 catch 块(或多个块)。如果发生的异常类型在 catch 块中列出,则异常将传递给 catch 块,就像将参数传递给方法参数一样。

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

异常中的流控制

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

如果没有发生异常 − 如果 try 块中没有引发异常,则 catch 块(在 try-catch 或 try-catch-finally 中)中的代码不会执行。无论如何,finally 块始终会执行(try-finally 或 try-catch-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("未找到给定的文件路径");
      }
   }
}

输出

未找到给定的文件路径

如果发生的异常未在 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

相关文章