静态代码块可以引发异常吗? [英] Can static code blocks throw exceptions?
本文介绍了静态代码块可以引发异常吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在一个假设的情况下,我有一个这样的课程:
In a hypothetical situation I have a class like this:
import java.io.File;
import java.util.Scanner;
class X
{
static Scanner scanner;
static
{
scanner = new Scanner(new File("X.txt"));
}
}
编译时,我得到
未报告的肽段
java.io.FileNotFoundException
;必须被抓到或声明要扔掉
unreported exeption
java.io.FileNotFoundException
; must be caught or declared to be thrown
因为 public Scanner(File source) throws FileNotFoundException
.
要解决此问题,我可以将scanner = new...
行放在try/catch语句中:
To fix this, I can put scanner = new...
line in a try/catch statement:
static
{
try
{
scanner = new Scanner(new File("X.txt"));
}
catch(Exception e)
{
e.printStackTrace();
}
}
但是,有什么办法可以做到:
However, is there any way I can do something like:
static throws java.io.FileNotFoundException
{
scanner = new Scanner(new File("X.txt"));
}
这是一种假设情况.请不要说那你为什么要这么做?"或这是制作扫描仪的更好方法!"
推荐答案
来自
如果类变量初始化程序(§8.7)可以抛出已检查的异常类.
It is a compile-time error if a class variable initializer (§8.3.2) or static initializer (§8.7) of a named class or interface can throw a checked exception class.
查看全文