Is it bad practice to catch the Exception class instead of Exception sub-classes?

后端 未结 5 2020
夕颜
夕颜 2021-01-26 11:38

I have a method which throws subclasses of Exception. If I am performing the same catch functionality for each sub-class of Exception that\'s causght is it bad practice to just

5条回答
  •  面向向阳花
    2021-01-26 12:12

    At some point, exceptions have to be handled. So there hopefully is a place in an application that handles (catches) all exceptions. Usually, this is a place where unexpected exceptions are caught to prevent complete application crashes and instead provide some path of recovery, along with some excusing message to the user. In general, in your classes, handle the expected failures and trust the contract your classes and methods provide to the caller. For example, in a method that fetches a record by an ID string from a database, do only catch the SQL exceptions, as your contract may clearly say that a null ID is not allowed. Throw back the bad input exceptions back to the caller, else you may end up validating user input at the wrong level.

提交回复
热议问题