Using try/catch for preventing app from crashes

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

    I have been developing android apps for the past 4-5 years and never used a try catch for view initialisation.

    If its a toolbar do like this

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    

    eg:- To get a TextView from a view(fragment/dialog/any custom view)

    TextView textview = (TextView) view.findViewById(R.id.viewId);
    

    TextView textview = (TextView) view.findViewById(R.id.viewId);

    instead of this

    View view = findViewById(R.id.toolbar);
    

    A view object has minimum reach compared to its real view type.

    Note:- May be it crashed because the view was loaded. But adding try catch is a bad practice.

提交回复
热议问题