Using try/catch for preventing app from crashes

前端 未结 14 1840
你的背包
你的背包 2021-01-30 03:37

I have been working on an Android app which uses try/catch frequently to prevent it from crashing even on places where there is no need. For example,

A view

14条回答
  •  清酒与你
    2021-01-30 04:32

    From the Android documentation:

    Let's entitle it as -

    Don't Catch Generic Exception

    It can also be tempting to be lazy when catching exceptions and do something like this:

    try {
        someComplicatedIOFunction();        // may throw IOException
        someComplicatedParsingFunction();   // may throw ParsingException
        someComplicatedSecurityFunction();  // may throw SecurityException
        // phew, made it all the way
    } catch (Exception e) {                 // I'll just catch all exceptions
        handleError();                      // with one generic handler!
    }
    

    In almost all cases it is inappropriate to catch generic Exception or Throwable (preferably not Throwable because it includes Error exceptions). It is very dangerous because it means that Exceptions you never expected (including RuntimeExceptions like ClassCastException) get caught in application-level error handling.

    It obscures the failure handling properties of your code, meaning if someone adds a new type of Exception in the code you're calling, the compiler won't help you realize you need to handle the error differently.

    Alternatives to catching generic Exception:

    • Catch each exception separately as separate catch blocks after a single try. This can be awkward but is still preferable to catching all Exceptions.
      Edit by author: This one is my choice. Beware repeating too much code in the catch blocks. If you are using Java 7 or above, use multi-catch to avoid repeating the same catch block.
    • Refactor your code to have more fine-grained error handling, with multiple try blocks. Split up the IO from the parsing, handle errors separately in each case.
    • Re-throw the exception. Many times you don't need to catch the exception at this level anyway, just let the method throw it.

    In most cases you shouldn't be handling different types of exception the same way.

    Formatting / paragraphing slightly modified from the source for this answer.

    P.S. Don't be afraid of Exceptions!! They are friends!!!

提交回复
热议问题