How to compare the caught exception against standard exceptions in asynchronous task android?

亡梦爱人 提交于 2019-12-10 02:58:53

问题


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:


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.



来源:https://stackoverflow.com/questions/7213073/how-to-compare-the-caught-exception-against-standard-exceptions-in-asynchronous

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!