【问题标题】:Android Exception handling best practiceAndroid 异常处理最佳实践
【发布时间】:2015-04-27 12:18:24
【问题描述】:

我有一些越来越少的大型 android 项目。现在我的代码中有很多try/catch 短语。有处理这些的最佳实践吗? 有时需要Toast,有时需要AlertDialog,有时甚至没有。 我的大部分异常处理都发生在 asynctasks 中,带有 Web 请求和 JSON 解析。

目前我是这样处理的: 我写了一个ErrorCase 类,我给它提供了contextthe classerror String

所以try/catch 看起来像这样

 try
 {
    HttpResponse response = httpclient.execute(httppost);
    //some more code

    if (statusLine.getStatusCode() != HttpStatus.SC_OK)
    {
        new ErrorCase(c, getClass().getSimpleName(), c.getString(R.string.errorHTTP));
    }
 }
 catch (ClientProtocolException e)
 {
    new ErrorCase(c, getClass().getSimpleName(), c.getString(R.string.errorClientProtocolException));
 }
 catch (UnsupportedEncodingException e)
 {
    new ErrorCase(c, getClass().getSimpleName(), c.getString(R.string.errorUnsupportedEncodingException));
 }
 catch (IOException e)
 {
    new ErrorCase(c, getClass().getSimpleName(), c.getString(R.string.errorIOException));
 }

还有像这样的ErrorCase

public class ErrorCase
{
    private Context main;
    private String className;
    private String reason;

    public ErrorCase(Context main, String className, String reason)
    {
        this.main = main;
        this.className = className;
        this.reason = reason;

        new Runnable()
        {
            public void run()
            {
                showToast();
            }
        };
    }

    private void showToast()
    {
        Toast.makeText(main, className.length() + "" + className.charAt(0) + className.charAt(className.length() - 1) + " " + reason, Toast.LENGTH_LONG).show();
        ((Activity) main).finish();
    }}

我愿意接受任何实用的通用建议。

提前致谢

【问题讨论】:

    标签: android exception generics


    【解决方案1】:

    在编写异常处理类之前,必须了解Checked vs Unchecked Exceptions。这个link 解释了它。

    现在,查看解释的代码hereThread.UncaughtExceptionHandler 是 当线程由于未捕获的异常而突然终止时调用的处理程序接口 - Oracle Docs

    这是另一个link,很好地解释了异常。

    【讨论】:

    • 感谢您的回答。我对未捕获的异常很好,现在我只是在寻找针对我捕获的异常是否有更漂亮的解决方案。
    猜你喜欢
    • 2013-05-09
    • 2018-01-03
    • 1970-01-01
    • 2017-05-11
    • 2011-11-10
    • 2013-04-22
    • 1970-01-01
    相关资源
    最近更新 更多