在 Java 中,不使用"throws Exception"子句是否可以抛出异常?

java 8object oriented programmingprogramming更新于 2025/6/27 7:37:17

当 Java 中发生异常时,程序会异常终止,并且导致异常的代码行之后的代码不会被执行。

要解决这个问题,您需要将导致异常的代码包装在 try catch 中,或者使用 throws 子句抛出异常。如果使用 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

当异常缓存在 catch 块中时,您可以使用 throw 关键字(用于抛出异常对象)重新抛出该异常。如果重新抛出异常,就像在 throws 子句中一样,此异常将在调用当前方法的方法中生成。

示例

在下面的 Java 示例中,我们在 demo method() 中的代码可能会抛出 ArrayIndexOutOfBoundsException 和 ArithmeticException。我们将在两个不同的 catch 块中捕获这两个异常。

在 catch 块中,我们将两个异常重新抛出,一个通过包装在更高级别的异常中,另一个直接抛出。

import java.util.Arrays;
import java.util.Scanner;
public class RethrowExample {
   public void demoMethod() {
      Scanner sc = new Scanner(System.in);
      int[] arr = {10, 20, 30, 2, 0, 8};
      System.out.println("Array: "+Arrays.toString(arr));
      System.out.println("Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)");
      int a = sc.nextInt();
      int b = sc.nextInt();
      try {
         int result = (arr[a])/(arr[b]);
         System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
      }
      catch(ArrayIndexOutOfBoundsException e) {
         throw new IndexOutOfBoundsException();
      }
      catch(ArithmeticException e) {
         throw e;
      }
   }
   public static void main(String [] args) {
      new RethrowExample().demoMethod();
   }
}

输出1

Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
0
4
Exception in thread "main" java.lang.ArithmeticException: / by zero
   at myPackage.RethrowExample.demoMethod(RethrowExample.java:16)
   at myPackage.RethrowExample.main(RethrowExample.java:25)

输出2

Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
124
5
Exception in thread "main" java.lang.IndexOutOfBoundsException
   at myPackage.RethrowExample.demoMethod(RethrowExample.java:17)
   at myPackage.RethrowExample.main(RethrowExample.java:23)

相关文章