简体   繁体   English

为什么我已经抛出未报告的异常 java.net.MalformedURLException?

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

Disclaimer: I haven't done Java in a long while.免责声明:我很久没有做过 Java。

I created this singleton class to create an HttpURLConnection.我创建了这个 singleton class 来创建一个 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 ?为什么我在setupConn中抛出未报告的MalformedURLException异常?

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

You are throwing the exception from setupConn function but you are not handling the thrown exception when you are calling it here:您正在从 setupConn function 抛出异常,但在此处调用它时您没有处理抛出的异常:

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.您可以使用 setupConn function 中的 try catch 处理异常,或者您可以在构造函数中调用 function 然后从那里重新抛出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM