2016-03-28 35 views
-1
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);」中顯示錯誤「 :「未處理的異常:java.lang.Exception的」未處理的異常如果調用HttpURLConnection

+0

後全堆棧跟蹤和具體。你用這個'httpCon.getResponseCode()'得到了什麼? –

回答

1

codeResult()方法拋出Exception

public int coderesult (String urlstring) throws Exception { 

因此,您必須追上它專門catch(Exception ex),或者宣佈從你的方法你扔了吧。

捕獲異常時,您要麼捕獲特定的異常類型,要麼捕獲更通用的父異常類型。您可以將所有漁獲物組合成一個陷阱,因爲所有的內置Java異常從異常

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

使用此

public int coderesult (String urlstring) throws IOException 

擴展和寫

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

@Andrey Andreev看到答案 – 2016-03-28 04:50:23