问题描述
我是java和android的初学者。我在我的项目中使用异步任务从Web服务中获取一些数据,在异常处理中遇到一些问题。我引用了这个,我按照CommonsWare在这个。我成功捕获异常并将其存储在异常变量中。我需要比较捕获的异常与 onPostExecute
方法中的某些标准异常,我也希望基于此显示自定义错误消息。如何将这个捕获的异常与标准异常进行比较?任何帮助将不胜感激。谢谢。
使用 Instanceof
java关键字。如果对象实例是正确的类型,则返回true。
if(e instanceof SomeStandardException)
注意: instanceof
对于确切类型和所有父类型。因此,如果您在级联的 if-elseif
中使用它,则将更多的具体类型放在最上方,并在底部使用更通用的(父类)类型。
Note2:捕获通用异常
如链接中提出的一个不好的做法 - 你应该只捕获你的异常想要处理所以不要保存exceptin,你应该通过 try-catch-catch
来捕捉一个具体的异常,保存适当的标志(布尔型字段),然后对这个标志执行操作。 p>
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 question and I am following the pattern suggested by CommonsWare in this link.
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.
Use Instanceof
java keyword. It returns true if object instance is of correct type.
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.
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.
这篇关于如何比较异常任务android中捕获的异常与标准异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!