java中的catch块可以重写吗

描述

当特定方法中的一段代码引发异常时,使用try-catch对进行处理。如果我们从另一个调用该方法,则调用行将包裹在try-catch对中。现在,如何通过调用方法的catch块覆盖catch块。

当方法中的一段代码引发异常(编译时)时,我们必须通过将其包装在try-catch对中来处理它,或者使用throws关键字将其抛出(推迟)到调用方法,否则会发生编译时错误。

在下面的Java示例中,readFile()方法中的代码生成FileNotFoundException,我们不对其进行处理。

示例

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ExceptionExample{
   public static String readFile(String path){
      String data = null;
      Scanner sc = new Scanner(new File("E://test//sample.txt"));
      String input;
      StringBuffer sb = new StringBuffer();
      sb.append(sc.next());
      data = sb.toString();
      return data;
   }
   public static void main(String args[]) {
      String path = "E://test//sample.txt";
      readFile(path);
   }
}

编译时错误

在编译时,以上程序会产生以下编译时错误。

ExceptionExample.java:7: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
         Scanner sc = new Scanner(new File("E://test//sample.txt"));
                                  ^
1 error

要解决此错误,我们需要使用try-catch对将异常处理为-

示例

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ExceptionExample{
   public static String readFile(String path){
      String data = null;
         try {
            Scanner sc = new Scanner(new File("E://test//sample.txt"));
            String input;
            StringBuffer sb = new StringBuffer();
            sb.append(sc.next());
            data = sb.toString();
         } catch (FileNotFoundException ex) {
            System.out.println("exception occurred");
         }
         return data;
   }
   public static void main(String args[]) {
      String path = "E://test//sample.txt";
      readFile(path);
   }
}

输出结果

exception occurred

或者,使用throws关键字将其抛出。如果这样做,则将异常推迟到此方法的调用行,即,该行现在发生错误。

示例

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ExceptionExample{
   public static String readFile(String path)throws FileNotFoundException {
      String data = null;
      Scanner sc = new Scanner(new File("E://test//sample.txt"));
      String input;
      StringBuffer sb = new StringBuffer();
      sb.append(sc.next());
      data = sb.toString();
      return data;
   }
   public static void main(String args[]) {
      String path = "E://test//sample.txt";
      readFile(path);
   }
}

编译时错误

ExceptionExample.java:17: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
      readFile(path);
               ^
1 error

要解决此问题,您需要包装调用行或使用throws关键字再次引发异常。

public static void main(String args[]) {
   String path = "E://test//sample.txt";
   OverridingException obj = new OverridingException();
   try {
      readFile(path);
   }catch(Exception ex) {
      System.out.println("Exception occured");
   }
}

话虽如此,如果您在source方法(最初生成异常的方法)中使用try-catch对处理异常,则无需在调用方法中再次处理它。在两个地方都有try-catch毫无意义。

在两个catch块中执行内容的唯一方法是重新引发异常。

重新抛出异常

当将异常缓存在catch块中时,可以使用throw关键字(用于抛出异常对象)将其重新抛出。

重新抛出异常时,您可以按原样抛出相同的异常,而无需对其进行调整

try {
   int result = (arr[a])/(arr[b]);
   System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
} catch(ArithmeticException e) {
   throw e;
}

或者,将其包装在新的异常中并抛出。当您将缓存的异常与另一个异常一起包装并引发异常时,这称为异常链接或异常包装,通过执行此操作,您可以调整异常,并抛出更高级别的异常来维护抽象。

try {
   int result = (arr[a])/(arr[b]);
   System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
} catch(ArrayIndexOutOfBoundsException e) {
   throw new IndexOutOfBoundsException();
}

示例

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ExceptionExample{
   public static String readFile(String path){
      String data = null;
         try {
            Scanner sc = new Scanner(new File("E://test//sample.txt"));
            String input;
            StringBuffer sb = new StringBuffer();
            sb.append(sc.next());
            data = sb.toString();
         }catch (FileNotFoundException ex){
            System.out.println("Exception occurred: source method");
         throw ex;
      }
      return data;
   }
   public static void main(String args[]) {
      String path = "E://test//sample.txt";
         try {
            readFile(path);
         }catch(Exception ex) {
            System.out.println("Exception occurred: calling method");
      }
   }
}

输出结果

Exception occurred: source method
Exception occurred: calling method