Should I catch and wrap general Exception?

前端 未结 14 1125
一向
一向 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条回答
  •  梦毁少年i
    2020-12-30 05:08

    You can use ellipses too.

       catch (...) 
       {
            // catches all exceptions, not already catches by a catch block before
            // can be used to catch exception of unknown or irrelevant type
       }
    

    Except this what you can do is nested try-catch

    try
    {
        //some code which is not for database related 
        try
        {
          //database related code with connection open
        }
        catch(//database related exception)
        {
            //statement to terminate
        }
        **finally()
        {
            //close connection,destroy object
        }**
    }
    catch(//general exception)
    {
        //statement to terminate
    }
    

    According to me, this would help you to get more concise idea of your error type.

提交回复
热议问题