问题
I have an internet operation that reads line from an online file. It is in a try-catch block. When the execution fails (for example for the missing internet connection) the operation go to catch block and the App crashes. How can I avoid crashes?
try {
BufferedReader reader = new BufferedReader(new InputStreamReader((new URL(MegaMethods.url+params[0])).openStream()), 8192);
String line;
while ((line = reader.readLine()) != null) {
count++;
}
reader.close();
}
catch (Exception e){
// Here I want to do something to avoid app crash
}
回答1:
Try to check if the device has network connectivity before trying to fetch the file. If no network is found, then avoid the task.
Code sample - Call this method. If it returns true, network is available.
public boolean isNetworkAvailable() {
boolean status=false;
try{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getNetworkInfo(0);
if (netInfo != null && netInfo.getState()==NetworkInfo.State.CONNECTED) {
status= true;
}else {
netInfo = cm.getNetworkInfo(1);
if(netInfo!=null && netInfo.getState()==NetworkInfo.State.CONNECTED)
status= true;
}
}catch(Exception e){
e.printStackTrace();
return false;
}
return status;
}
Also, I agree with you that, for some reason, application might throw exception and reaches Catch block. But please note that, even if the catch block is empty, it will not crash your application.
Application might crash because of some code outside the try catch block.
来源:https://stackoverflow.com/questions/27809207/avoid-app-crashing-when-catch-exception