在 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)
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP