我们可以在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