Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 532
S1lentSt0rm Avatar asked Dec 27 '22 12:12

S1lentSt0rm


1 Answers

You can just catch it and rethrow as an AssertionError:

try {
    this.url = new URL(url);
}
catch(MalformedURLException e) {
    throw new AssertionError(e);
}
like image 128
yshavit Avatar answered Jan 03 '23 09:01

yshavit