Using try/catch for preventing app from crashes

前端 未结 14 1844
你的背包
你的背包 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:38

    As said before, general exceptions shouldn't be catched, or at least only in a few central places (usually located in framework/infrastructure code, not application code). If catching general exceptions and logging it, the application should be shut down afterwards, or at the very least user should be informed that application is potentially in a unstable state and data corruption could occur (if user chooses to continue execution). Because this is what might happen if you catch all sort of exceptions (out of memory to name one) and leaving the app in an undefined state.

    IMHO it is worse to swallow exceptions and risk data integrity, data loss, or simply leaving the app in an undefined state than letting the app crash and the user knows that something went wrong and can try again. This will also lead to better issues reported (more at the root of the problem), probably fewer different symptoms than if your users start to report all kind of troubles originating from undefined application state.

    After a central exception handling/logging/reporting and controlled shutdown is in place, start rewriting exception handling to catch local exceptions as specific as possible. Try to make the try{} block as short as possible.

提交回复
热议问题