避免在捕获异常时应用崩溃 [英] Avoid App crashing when catch Exception

查看:60
本文介绍了避免在捕获异常时应用崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个互联网操作,可以从在线文件中读取行.它在try-catch块中.当执行失败时(例如,由于缺少互联网连接),该操作转到catch块,应用崩溃.如何避免当机?

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
    }

推荐答案

在尝试获取文件之前,请尝试检查设备是否具有网络连接.如果找不到网络,请避免执行该任务.

Try to check if the device has network connectivity before trying to fetch the file. If no network is found, then avoid the task.

代码示例-调用此方法.如果返回true,则表明网络可用.

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;

    } 

此外,我也同意您的意见,由于某种原因,应用程序可能会引发异常并到达Catch块.但是请注意,即使catch块为空,也不会使您的应用程序崩溃.

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.

由于try catch块之外的某些代码,应用程序可能会崩溃.

Application might crash because of some code outside the try catch block.

这篇关于避免在捕获异常时应用崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆