Using try/catch for preventing app from crashes

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

    This is bad for multiple reasons:

    1. What are you doing that findViewById throws an Exception? Fix that (and tell me, because I've never seen this) instead of catching.
    2. Don't catch Exception when you could catch a specific type of exception.
    3. There is this belief that good apps don't crash. That's not true. A good app crashes if it must.

    If an app goes into a bad state, it is much better for it to crash than for it to chug along in its unusable state. When one sees an NPE, one shouldn't just stick in a null check and walk away. The better approach is to find out why something is null and either stop it from being null, or (if null ends up being a valid and expected state) check for null. But you have to understand why the issue occurs in the first place.

提交回复
热议问题