简体   繁体   English

如何从枚举构造函数中抛出异常

[英]How to throw an exception from an enum constructor

(Referring to this post: How to throw an exception from an enum constructor? ) (参考这篇文章:如何从枚举构造函数中抛出异常?

I would really like to do the same.我真的很想做同样的事情。 Example Code:示例代码:

public enum PublicIPWebservice {
    AMAZON_WEB_SERVICES("http://checkip.amazonaws.com"),
    EX_IP("http://api-ams01.exip.org/?call=ip"),
    WHAT_IS_MY_IP("http://automation.whatismyip.com/n09230945.asp");

private URL url;

private PublicIPWebservice(String url) throws MalformedURLException {
    this.url = new URL(url);
}

public URL getURL() {
    return url;
}
}

The program should crash if the url was not correct, as it would be a programming mistake, so catching the exception in the constructor would be wrong, wouldn't it?如果 url 不正确,程序应该会崩溃,因为这将是一个编程错误,所以在构造函数中捕获异常是错误的,不是吗?

What is the best way to solve that problem?解决该问题的最佳方法是什么?

You can just catch it and rethrow as an AssertionError: 您可以捕获它并重新抛出AssertionError:

try {
    this.url = new URL(url);
}
catch(MalformedURLException e) {
    throw new AssertionError(e);
}

I would just throw a RuntimeExpcetion of some kind (for example IllegalArgumentException ) 我会抛出某种RuntimeExpcetion (例如IllegalArgumentException

private PublicIPWebservice(String url) {
    try {
        this.url = new URL(url);
    catch (MalformedURLException e) {
        throw new IllegalArgumentException(e);
    }
}

Usually a programmer error must be reported as an unchecked exception since it "will not occur" so theres no need to force yourself to catch the exception in client class. 通常程序员错误必须报告为未经检查的异常,因为它“不会发生”所以不需要强迫自己捕获客户端类中的异常。

That said you should wrap the url creation and throw an unchecked exception. 那说你应该包装url创建并抛出一个未经检查的异常。

private PublicIPWebservice(String url) {
    try {
        this.url = new URL(url);
    catch (MalformedURLException ex) {
        throw new IllegalArgumentException("From input: " + url);
    }
}

Throwing an IllegalArgumentException is a good choice. 抛出IllegalArgumentException是一个不错的选择。

Why wouldn't you want to catch that exception? 为什么你不想要赶上例外?

private PublicIPWebservice(String url) {
    try {
        this.url = new URL(url);
    catch (MalformedURLException e) {
        // surely you should handle the exception here
    }
}

What is the first user of this enum going to do with an exception. 这个枚举的第一个用户与异常有什么关系。 IT certainly wouldn't be expecting one. IT当然不会期待一个。

如果您真的希望程序“崩溃”(终止), System.exit(n)是(我认为)唯一的绝对保证,没有人会处理一些异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM