调用httpurlconnection时出现未处理的异常

bnl4lu3b  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(310)
public  int coderesult (String urlstring) throws Exception {
    URL url = new URL(urlstring);
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    //System.out.println("Response code is " + httpCon.getResponseCode());
    int mycode = httpCon.getResponseCode();
    return mycode;
}
public int displaycode () {
    int dispcode = 0;
    try {
        dispcode = coderesult(myurl);

    }
    catch (MalformedURLException e){
        e.printStackTrace();
    }catch(IOException e){
        e.printStackTrace();
    }finally {
    }
    return dispcode;
}

android studio在“dispcode=coderesult(myurl);”中显示错误:未处理exception:java.lang.exception"

5t7ly7z5

5t7ly7z51#

你的 codeResult() 方法抛出 Exception ```
public int coderesult (String urlstring) throws Exception {

因此,你必须要么抓住它具体 `catch(Exception ex)` ,或声明从方法中抛出它。
捕捉异常时,可以捕捉特定的异常类型,也可以捕捉更通用的父异常类型。您可以将所有捕获组合成一个捕获,因为所有内置的java异常都是从exception扩展而来的

catch(Exception ex){
ex.printStackTrace();
}

nvbavucw

nvbavucw2#

用这个

public  int coderesult (String urlstring) throws IOException

写下

catch(IOException ie) {
            ie.printStackTrace();
}

相关问题