在 Java 中,是否可以在不使用“throws Exception”的情况下抛出异常?


当 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)

更新于: 2019年9月6日

3K+ 浏览量

启动您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.