我們可以在Java的靜態塊中丟擲未檢查異常嗎?
靜態塊是一段帶有static關鍵字的程式碼塊。通常,它們用於初始化靜態成員。JVM在類載入時,在main方法之前執行靜態塊。
示例
public class MyClass {
static{
System.out.println("Hello this is a static block");
}
public static void main(String args[]){
System.out.println("This is main method");
}
}輸出
Hello this is a static block This is main method
靜態塊中的異常
就像Java中的任何其他方法一樣,當靜態塊中發生異常時,可以使用try-catch對來處理它。
示例
import java.io.File;
import java.util.Scanner;
public class ThrowingExceptions{
static String path = "D://sample.txt";
static {
try {
Scanner sc = new Scanner(new File(path));
StringBuffer sb = new StringBuffer();
sb.append(sc.nextLine());
String data = sb.toString();
System.out.println(data);
} catch(Exception ex) {
System.out.println("");
}
}
public static void main(String args[]) {
}
}輸出
This is a sample fileThis is main method
在靜態塊中丟擲異常
每當你丟擲一個檢查異常時,你需要在當前方法中處理它,或者你可以將其丟擲(推遲)到呼叫方法。
You cannot use throws keyword with a static block, and more over a static block is invoked at compile time (at the time of class loading) no method invokes it.
因此,如果你在靜態塊中使用throw關鍵字丟擲異常,則必須將其包裝在try-catch塊中,否則將生成編譯時錯誤。
示例
import java.io.FileNotFoundException;
public class ThrowingExceptions{
static String path = "D://sample.txt";
static {
FileNotFoundException ex = new FileNotFoundException();
throw ex;
}
public static void main(String args[]) {
}
}編譯時錯誤
ThrowingExceptions.java:4: error: initializer must be able to complete normally
static {
^
ThrowingExceptions.java:6: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
throw ex;
^
2 errors
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP