Java:异常抛出类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2632249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:06:37  来源:igfitidea点击:

Java: exception-throwing class?

javaexceptionclasserror-handling

提问by hhh

I have classes DirReader and Search. The search uses DirReader. I want the search to know when DirReader throws exception. So how can I have class throwing exception?

我有类 DirReader 和 Search。搜索使用 DirReader。我希望搜索知道 DirReader 何时抛出异常。那么我怎样才能让类抛出异常呢?

Currently, I use initCorrect -dummy var. Exception-style method may be more appropriate.

目前,我使用 initCorrect -dummy var。异常风格的方法可能更合适。

Simplified Example Error

简化示例错误

$ javac ExceptionStatic.java 
ExceptionStatic.java:4: '{' expected
public class ExceptionStatic throws Exception{
                            ^
1 error

Code

代码

import java.util.*;
import java.io.*;

// THIS PART NEEDS TO BE FIXED:
public class ExceptionStatic throws Exception{

    private static boolean initCorrect = false;

    public static String hello;
    static{
        try{
            hello = "hallo";

            //some other conditionals in real code
            if( true) throw new Exception();

            initCorrect=true;
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        if(initCorrect)
            System.out.println(hello);
    }
}

采纳答案by erickson

It is a compile-time error for a class initializer ("static block") to terminate with a checked exception.

类初始值设定项(“静态块”)以已检查的异常终止是编译时错误。

If a class initializer throws an uncheckedexception, the first attempt to initialize the class will raise an ExceptionInInitializeError. Any subsequent attempts to use the class will cause a NoClassDefFoundError. If you really want to use an exception, throw something like a RuntimeExceptionin the initializer.

如果类初始值设定项抛出未经检查的异常,则第一次尝试初始化该类将引发ExceptionInInitializeError. 任何后续尝试使用该类都将导致NoClassDefFoundError. 如果您真的想使用异常,请RuntimeException在初始化程序中抛出类似 a的内容。

However, the approach shown in the question—setting a flag when the class is initialized correctly—might actually be a better one for many applications. More specifically, I'd say that unless you want the whole program to terminate when there's a initialization failure, use a flag. Just remove the "throws" clause from the class declaration, because that isn't a legal syntax.

但是,问题中显示的方法(在正确初始化类时设置标志)对于许多应用程序实际上可能是更好的方法。更具体地说,我会说除非您希望整个程序在初始化失败时终止,否则请使用标志。只需从类声明中删除“throws”子句,因为这不是合法的语法。

回答by Jonathon Faust

Classes cannot throw exceptions. Only methods may throw exceptions. Avoid using the base Exceptionclass. Throw a specific exception like IllegalStateException or extend Exceptionand make your own.

类不能抛出异常。只有方法可以抛出异常。避免使用基Exception类。抛出一个特定的异常,比如 IllegalStateException 或扩展Exception并创建你自己的异常。

回答by Amir Afghani

You have a static code block that throws an exception? If you really need to do this throw a RuntimeException- otherwise move your logic into a method associated with a DirReader or Search class and have those methods throw the appropriate Exception.

您有一个会引发异常的静态代码块吗?如果您真的需要这样做,则抛出一个RuntimeException- 否则将您的逻辑移动到与 DirReader 或 Search 类关联的方法中,并让这些方法抛出适当的Exception.

Here's an example you can start with:

这是您可以开始的示例:

public class test { 


    static {
        try {
            method1();
        } catch (InterruptedException e) {
            throw new RuntimeException();
        }
    }

    protected static void method1() throws InterruptedException {        
        Thread.sleep(1000);        
    }


}

回答by fastcodejava

The throwskeyword cannot be applied at class level, only at the method level.

throws关键字不能在类级仅在方法级别施加。

回答by Hosein Abdollahipoor

You can't throw an exception in class definition. You should throw your exception in method definition or use try-catch block.

您不能在类定义中抛出异常。您应该在方法定义中抛出异常或使用 try-catch 块。