Avoid App crashing when catch Exception

喜夏-厌秋 提交于 2021-02-08 10:42:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!