\n如何在Java的靜態塊中丟擲異常?\n
靜態塊是一組語句,將在JVM執行main()方法之前執行。如果在類載入時想要執行任何操作,則必須在靜態塊內定義該操作,因為此塊在類載入時執行。
從靜態塊丟擲異常
- 靜態塊只能丟擲執行時異常,或者應該使用try和catch塊來捕獲檢查異常。
- 靜態塊在類載入器載入類時發生。程式碼可以以靜態塊的形式出現,也可以作為靜態方法的呼叫來初始化靜態資料成員。
- 在這兩種情況下,編譯器都不允許檢查異常。當發生未檢查異常時,它會被ExceptionInInitializerError包裝,然後在觸發類載入的執行緒的上下文中丟擲。
- 嘗試從靜態塊丟擲檢查異常也是不可能的。我們可以在靜態塊中使用try和catch塊,其中檢查異常可能從try塊丟擲,但必須在catch塊中解決它。我們不能使用throw關鍵字進一步傳播它。
示例
public class StaticBlockException { static int i, j; static { System.out.println("In the static block"); try { i = 0; j = 10/i; } catch(Exception e){ System.out.println("Exception while initializing" + e.getMessage()); throw new RuntimeException(e.getMessage()); } } public static void main(String args[]) { StaticBlockException sbe = new StaticBlockException(); System.out.println("In the main() method"); System.out.println("Value of i is : "+i); System.out.println("Value of j is : "+ j); } }
輸出
In the static block Exception while initializing/ by zero Exception in thread "main" java.lang.ExceptionInInitializerError Caused by: java.lang.RuntimeException: / by zero at StaticBlockException.(StaticBlockException.java:10)
廣告