ribot / android-guidelines

Architecture and code guidelines we use at ribot when developing for Android

Home Page:http://ribot.co.uk/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Guideline about generic exceptions is misleading

matt-quigley-ck opened this issue · comments

Just FYI - The code guidelines comment about not catching generic exceptions actually refers to a link in the Android OS source guidelines. That is, it is a guideline about writing the operating system code, not generic Android applications.

It is appropriate to catch generic exceptions in your code in many places, such as the bottom of a network library's main entry or the loop of a game. Even the Android OS will catch Throwables at the bottom of their message loops; they just don't want a random developer to prevent those Throwables from not reaching said loops.

Otherwise, this guideline is encouraging application crashes for unknown errors.

That being said... it is an appropriate guideline that an Android application should not catch generic exceptions except at the "bottom" of such locations, and not in most places (to be fair, the example given is a good example of when not to catch generic exceptions).

I agree that when writing application code there are cases where is reasonable to catch generic exceptions but generally it's preferable to catch specific exceptions instead of general ones.

Would you suggest to remove that section from the guidelines or rephrase it?

I think it's a good idea to encourage developers to catch specific exceptions over general ones, so I'd just add a disclaimer mentioning it. In fact, in the guidelines, I didn't even notice this earlier but they've actually already described what I said:

There are rare exceptions to this rule: certain test code and top-level code where you want to catch all kinds of errors (to prevent them from showing up in a UI, or to keep a batch job running). In that case you may catch generic Exception (or Throwable) and handle the error appropriately. You should think very carefully before doing this, though, and put in comments explaining why it is safe in this place.

Guess I'm a little pedantic here; maybe just say "You should not do this, except in certain rare cases:"