我是java和android的初学者。我在项目中使用异步任务从 Web 服务获取一些数据,在异常处理中遇到了一些问题。我提到了这个SO问题,并且我遵循CommonsWare在此链接。
我成功捕获了异常并将其存储在异常变量中。我需要将捕获的异常与 onPostExecute 方法中的一些标准异常进行比较,我也想基于此显示自定义错误消息。如何将此捕获的异常与标准异常进行比较?任何帮助将不胜感激。谢谢。
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.
发布评论
评论(1)
使用
Instanceof
java 关键字。如果对象实例的类型正确,则返回 true。注意:
instanceof
对于精确类型和所有父类型都返回 true。因此,如果您在级联if-elseif
中使用它,则将更具体的类型放在顶部,将更通用(父)类型放在底部。注意2:按照链接中的建议捕获通用
Exception
是一种不好的做法 - 您应该只捕获您想要处理的异常。因此,您应该通过 try-catch-catch 捕获具体的异常,而不是保存异常,保存适当的标志(可能是布尔字段),然后对该标志进行操作。Use
Instanceof
java keyword. It returns true if object instance is of correct type.Note:
instanceof
returns true for both exact type and all parent types. So if you use it in a cascadingif-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 viatry-catch-catch
, save appropriate flag (boolean field maybe) and then act on this flag.