Using try/catch for preventing app from crashes

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

    While I agree with the other responses, there is one circumstance I have repeatedly encountered where this motif is marginally tolerable. Suppose someone wrote a bit of code for a class as follows:

    private int foo=0;
    
        . . .
    
    public int getFoo() throws SomeException { return foo; }
    

    In this circumstance, the 'getFoo()' method cannot fail - there will always be a legitimate value of the private field 'foo' to be returned. Yet someone - probably for pedantic reasons - decided that this method should be declared as potentially throwing an Exception. If you then try to call this method in a context - e.g an event handler - which does not allow an exception to be thrown, you are basically forced to use this construct (even then, I agree that one should at least log the exception just in case). Whenever I have to do this, I always at least add a big fat comment 'THIS CANNOT OCCUR' next to the 'catch' clause.

提交回复
热议问题