Ted
Ted

Reputation: 1690

Catching an exception when instantiating a class field

I want to instantiate a URL as a private field in a class, but I can't catch the MalformedURLException. I've tried using a static initialization block, but that doesn't work either. How do I solve this?

public class MyClass{ 

    private final static URL DEFAULT_URL = new URL("http://www.yadayada.com?wsdl")

    ...
}

Upvotes: 0

Views: 155

Answers (5)

Harish Kumar
Harish Kumar

Reputation: 528

Try below. you cannot use final keyword for below:

private static URL DEFAULT_URL = null;
    static{
        try {
            DEFAULT_URL = new URL("http://www.yadayada.com?wsdl");
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

Upvotes: 0

Alex Turbin
Alex Turbin

Reputation: 2702

Using static block initializer - you may catch exception inside the block.

However, I would not recommend to store it as final class field as URI. Place it as String constant and initialize in constructor or special init() intance method

Upvotes: 0

assylias
assylias

Reputation: 328618

A simple workaround is to create a static method:

private final static URL DEFAULT_URL = getDefaultUrl();

private static URL getDefaultUrl() {
    try {
        return new URL("http://www.yadayada.com?wsdl"); 
    } catch (Exception e) {
        //what do you want to do here?
        return null; //that is an option
        throw new AssertionError("Invalid URL"); //that is another one
    }
}

Upvotes: 5

Chen Harel
Chen Harel

Reputation: 10052

You can do it in the static block

public class MyClass { 

    private final static URL DEFAULT_URL; 

    static {
      try {
       DEFAULT_URL = new URL("http://www.yadayada.com?wsdl");
    } catch (MalformedURLException e) {
    }
}

Upvotes: 1

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

You will need to throw something in the case of an exception. An Error should do the job.

public class MyClass{ 

    private static final URL DEFAULT_URL;
    static {
        try {
            DEFAULT_URL = new URL("http://www.yadayada.com?wsdl")
        } catch (java.net.MalformedURLException exc) {
            throw new Error(exc);
        }
    }
    ...
}

In case an exception is thrown (it shouldn't be) the class will fail to initialse.

Upvotes: 6

Related Questions