Java 中的 Throw 和 throws

java 8object oriented programmingprogramming更新于 2025/11/7 8:12:17

throws 关键字

每当方法中发生异常时,您需要通过将导致异常的代码包装在 try-catch 块中来处理它,或者,您可以使用 throws 关键字将其抛出/推迟到调用方法。然后,您需要在调用方法中处理异常。

Example

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);
   }
}

输出

Compile-time error

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 occurred");
   }
}

throw 关键字

您可以使用 throw 关键字显式抛出用户定义异常或预定义异常。

异常有两种类型:用户定义异常和预定义异常。每种异常都由一个类表示,并继承自 Throwable 类。

要显式抛出异常,您需要实例化该类并使用 throw 关键字抛出其对象。

示例

以下 Java 程序抛出 NullPointerException

public class ExceptionExample {
   public static void main(String[] args) {
      System.out.println("Hello");
      NullPointerException nullPointer = new NullPointerException();
      throw nullPointer;
   }
}

输出

Hello
Exception in thread "main" java.lang.NullPointerException
   at July_set2.ExceptionExample.main(ExceptionExample.java:6)

每当您显式抛出异常时,都需要确保带有 throw 关键字的行是程序的最后一行。这是因为在此行之后编写的任何代码都是无法访问的代码,并且如果您在此行之后仍有代码片段,则会产生编译时错误。

示例

public class ExceptionExample {
   public static void main(String[] args) {
      System.out.println("Hello");
      NullPointerException nullPointer = new NullPointerException();
      throw nullPointer;
      System.out.println("How are you");
   }
}

输出

Compile-time error

D:\>javac ExceptionExample.java
ExceptionExample.java:6: error: unreachable statement
   System.out.println("How are you");
   ^
1 error

重新抛出异常

当异常被缓存在 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();
}

示例

在下面的 Java 示例中,演示方法 () 中的代码可能会抛出 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)

相关文章