java 如何将捕获的异常与异步任务android中的标准异常进行比较?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7213073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compare the caught exception against standard exceptions in asynchronous task android?
提问by Sandeep
I am a beginner in both java and android. I am using asynchronous task in my project to fetch some data from a web service, faced some problems in exception handling. I referred this SO questionand I am following the pattern suggested by CommonsWare in this link.
我是java和android的初学者。我在我的项目中使用异步任务从 Web 服务中获取一些数据,在异常处理中遇到了一些问题。我提到了这个SO 问题,我正在遵循 CommonsWare 在此链接中建议的模式。
I succeeded in catching the exceptions and storing it in an exception variable. I need to compare the caught exception against some standard exceptions in onPostExecute
method also I would like to display custom error messages based on that. How can I compare this caught exception against standard exceptions? Any help would be appreciated. Thank you.
我成功地捕获了异常并将其存储在异常变量中。我需要将捕获的异常与onPostExecute
方法中的一些标准异常进行比较,我还想基于此显示自定义错误消息。如何将捕获的异常与标准异常进行比较?任何帮助,将不胜感激。谢谢你。
回答by Peter Knego
Use Instanceof
java keyword. It returns true if object instance is of correct type.
使用Instanceof
java 关键字。如果对象实例的类型正确,则返回 true。
if(e instanceof SomeStandardException)
Note:instanceof
returns true for both exact type and all parent types. So if you use it in a cascading if-elseif
then put more concrete types at the top and more generic (parent) types at the bottom.
注意:instanceof
对于精确类型和所有父类型都返回 true。因此,如果您在级联中使用它,if-elseif
则在顶部放置更多具体类型,在底部放置更多通用(父)类型。
Note2:catching generic Exception
as proposed in the link is a bad practice - you should only catch exceptions that you want to handle. So instead of saving the exceptin, you should catch a concrete exception via try-catch-catch
, save appropriate flag (boolean field maybe) and then act on this flag.
注意2:Exception
按照链接中的建议捕获泛型是一种不好的做法 - 您应该只捕获要处理的异常。因此,与其try-catch-catch
保存异常,您应该通过 捕获一个具体的异常,保存适当的标志(可能是布尔字段),然后对这个标志采取行动。