Should I catch and wrap general Exception?

前端 未结 14 1165
一向
一向 2020-12-30 04:19

Can following code be considered as a good practice? If not, why?

try
{
    // code that can cause various exceptions.         


        
14条回答
  •  南笙
    南笙 (楼主)
    2020-12-30 04:56

    The general principal with Exceptions is to catch them and handle them locally if applicable and otherwise allow them to bubble up to the top level container.

    It all depends on the context that your application is running in. For example if the application is an ASP.Net web application then certain exceptions can be handled by the ASP application server in IIS but expected application specific errors (ones that are defined in your own interfaces) should be caught and presented to the end user if appropriate.

    If you are dealing with I/O then there are a lot of factors that are beyond your control (network availability, disk hardware, etc.) so if there is a failure here then it is a good idea to deal with it straight away by catching the exception and presenting the user with and error message.

    Most importantly don't fail silently so don't wrap the exceptions in your own exception and then ignore them. Better to allow them to bubble up and find them in the web server log for example.

提交回复
热议问题