静态代码块可以引发异常吗? [英] Can static code blocks throw exceptions?

查看:527
本文介绍了静态代码块可以引发异常吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个假设的情况下,我有一个这样的课程:

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"));
    }

这是一种假设情况.请不要说那你为什么要这么做?"或这是制作扫描仪的更好方法!"

推荐答案

来自

如果类变量初始化程序(

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.

为了完整性,在

RuntimeException及其所有子类共同是运行时异常类.

RuntimeException and all its subclasses are, collectively, the run-time exception classes.

未经检查的异常类是运行时异常类和错误类.

The unchecked exception classes are the run-time exception classes and the error classes.

这是可以从静态初始化程序引发的唯一异常类型.

This is the only type of exception that can be thrown from a static initializer.

这篇关于静态代码块可以引发异常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆