Why do Java people frequently consume exceptions silently?

前端 未结 28 1631
傲寒
傲寒 2020-11-29 17:50

I never did any serious Java coding before, but I learned the syntax, libraries, and concepts based on my existing skills (Delphi & C#). One thing I hardly understand i

28条回答
  •  既然无缘
    2020-11-29 18:09

    The real point of exceptions is to simplify error handling and separate it from error detection. This is in contrary to representing errors by error codes, where error handling code is scattered everywhere and every call which may fail shall be checked for return code.

    If exception represents an error (which is most of the cases) usually the most reasonable way to handle it is to bail out and leave the handling to some upper layer. Rethrowing different exception should be considered if some meaningful semantics is added to it i.e., this error is an unusual system failure / temporary (networking) problem / this is client or server side error etc.

    Of all error handling strategies the most ignorant is hiding or simply printing error message and going forward as nothing happened.


    Sun folks wanted the code to be more explicit and forced programmers to write which exceptions may be thrown by which method. It seemed to be right move -- anybody will known what to expect in return from any method call given it's prototype (it may return value of this type or throw an instance of one of the specified classes (or it's subclass)).

    But as it turned out with lots of ignorant Java programmers they now treat exception handling as if it was a language bug/"feature" which needed a workaround and write code in worst or almost worst possible way:

    • The error is handled right away in context not suitable to decide what to do with it.
    • It is displayed or ignored silently and computing continues even when further code has no chance to run properly.
    • The caller of method can not differentiate whether it finished successfully or not.

    How to write the "right way" than?

    • Indicate every base class of exceptions which can be thrown in method header. AFAICR Eclipse can do it automatically.
    • Make the throw list in method prototype meaningful. Long lists are pointless and "throw Exception" is lazy (but useful when you not bother much about exceptions).
    • When writing the "wrong way" simple "throw Exception" is much better and takes less bytes than "try{ ... } catch(Exception e) { e.printStackTrace(); }".
    • Rethrow chained exception if needed.

提交回复
热议问题