【发布时间】:2015-04-27 12:18:24
【问题描述】:
我有一些越来越少的大型 android 项目。现在我的代码中有很多try/catch 短语。有处理这些的最佳实践吗?
有时需要Toast,有时需要AlertDialog,有时甚至没有。
我的大部分异常处理都发生在 asynctasks 中,带有 Web 请求和 JSON 解析。
目前我是这样处理的:
我写了一个ErrorCase 类,我给它提供了context、the class 和error 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