简体   繁体   中英

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?

What is the best way to solve that problem?

You can just catch it and rethrow as an 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 )

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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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