我们能从 Java 中的静态块中抛出未检查异常吗?
java 8object oriented programmingprogramming更新于 2025/11/21 3:24:17
静态块是带有 static 关键字的代码块。通常,它们用于初始化静态成员。JVM 在类加载时在主方法之前执行静态块。
示例
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
在静态块中抛出异常
每当您抛出已检查的异常时,您都需要在当前方法中处理它,或者您可以将其抛出(推迟)到调用方法。
您不能将 throws 关键字与静态块一起使用,而且静态块是在编译时(在类加载时)调用的,没有方法会调用它。
因此,如果您在静态块中使用 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

