Why am I getting a unreported exception java.net.MalformedURLException when I'm throwing it already?

333 views Asked by At

Disclaimer: I haven't done Java in a long while.

I created this singleton class to create an HttpURLConnection.

public class EstablishConnection {
    HttpURLConnection conn = setupConn("some url");
    private static final EstablishConnection instance = new EstablishConnection();
    
    //private constructor to avoid client applications to use constructor
    private EstablishConnection(){}
​
    public static EstablishConnection getInstance(){
        return instance;
    }
    
    private static HttpURLConnection setupConn(String addr) throws MalformedURLException, IOException, ProtocolException {
        URL url = new URL(addr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        return conn;
    }
}
​

Why am I getting an unreported MalformedURLException exception when I'm throwing it in setupConn?

|       HttpURLConnection conn = setupConn("some url");
unreported exception java.net.MalformedURLException; must be caught or declared to be thrown
1

There are 1 answers

0
Faizan Burney On BEST ANSWER

You are throwing the exception from setupConn function but you are not handling the thrown exception when you are calling it here :

HttpURLConnection conn = setupConn("some url");

you can handle the exception using try catch in the setupConn function or you can call the function in the the constructor and then rethrow from there.