What should be the best Exception Handling Strategy

后端 未结 7 2014
逝去的感伤
逝去的感伤 2021-02-14 07:28

I am working on application where user invokes a method from UI , on this I am calling a method from business class which calls another methods

UI--> Method1 -->Method2

7条回答
  •  [愿得一人]
    2021-02-14 08:25

    The basic rule is "Don't catch exceptions when you cannot handle it." So any unexpected exception should ultimately tell the user that something went wrong and shut down the application as gracefully as possible. Not shutting down the application is risky because the state might be corrupted and in turn corrupt information important to the user.

    Robust applications are modular so that the application can recover without shutting down by stopping or restarting single components like services or plugins.

    There are some cases where you might want to catch exceptions that you cannot handle but then the exception should either be re-thrown or a new exception should be thrown.

    If you want to log exceptions you will catch, log and re-throw.

    If you want to improve the error message you will catch, wrap in a new exception, and throw. For example you may want to wrap a generic FileNotFoundException when reading a file in a new exception with a more descriptive message telling the user what file could not be found.

提交回复
热议问题