S1lentSt0rm
S1lentSt0rm

Reputation: 2039

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?

Upvotes: 4

Views: 4252

Answers (5)

barneypitt
barneypitt

Reputation: 1172

If you really want the program to "crash" (terminate), System.exit(n) is (I think) the only absolute guarantee that nothing and nobody will handle some exception.

Upvotes: 0

yshavit
yshavit

Reputation: 43391

You can just catch it and rethrow as an AssertionError:

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

Upvotes: 7

lpinto.eu
lpinto.eu

Reputation: 2127

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.

Upvotes: 1

Aviram Segal
Aviram Segal

Reputation: 11120

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);
    }
}

Upvotes: 2

Bohemian
Bohemian

Reputation: 425188

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.

Upvotes: 0

Related Questions