调用 HttpURLConnection 时出现未处理的异常
Unhandled exception if call HttpURLConnection
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);" 中显示错误:"Unhandled exception:java.lang.Exception"
您的 codeResult()
方法抛出 Exception
public int coderesult (String urlstring) throws Exception {
因此,您必须专门捕获它 catch(Exception ex)
,或者声明从您的方法中抛出它。
捕获异常时,您要么捕获特定的异常类型,要么捕获更通用的父异常类型。您可以将所有捕获合并为一个捕获,因为所有内置 java 异常都从 Exception
扩展
catch(Exception ex){
ex.printStackTrace();
}
使用这个
public int coderesult (String urlstring) throws IOException
然后写
catch(IOException ie) {
ie.printStackTrace();
}
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);" 中显示错误:"Unhandled exception:java.lang.Exception"
您的 codeResult()
方法抛出 Exception
public int coderesult (String urlstring) throws Exception {
因此,您必须专门捕获它 catch(Exception ex)
,或者声明从您的方法中抛出它。
捕获异常时,您要么捕获特定的异常类型,要么捕获更通用的父异常类型。您可以将所有捕获合并为一个捕获,因为所有内置 java 异常都从 Exception
扩展catch(Exception ex){
ex.printStackTrace();
}
使用这个
public int coderesult (String urlstring) throws IOException
然后写
catch(IOException ie) {
ie.printStackTrace();
}