(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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With