I've caught an exception!! Now what?

后端 未结 16 905
逝去的感伤
逝去的感伤 2021-02-02 05:15

I\'ve started using try-catch blocks (a bit late, I know!), but now I\'m not sure what to do with the exception once I\'ve caught it. What should I do?



        
16条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-02 05:33

    I'd like to suggest to you that if you do not know what to do with an exception, do not catch it. Too often, coders catch exceptions and just swallow them whole.

    catch (Exception ex)
    {
      /* I don't know what to do.. *gulp!* */
    }
    

    Clearly this isn't good, because bad things are happening, and no action is being taken. Only catch exceptions that are actionable!

    That said, graceful error handling is important. Don't want your app to crash, right? You may find ELMAH useful for web applications, and a global exception handler is pretty easy to set up for WinForms or XAML desktop apps.

    Putting all that together, you might find this strategy useful: 1. catch specific exceptions that you know might occur (DivideByZeroException, SQLException, etc.) and steer away from the generic catch-all Exception; 2. re-raise the exception after you handle it. e.g.

    catch (SQLException ex)
    {
      /* TODO: Log the error somewhere other than the database... */
      throw; // Rethrow while preserving the stack trace.
    }
    

    What can you really do with an SQLException? Did the database connection disappear? Was it a bad query? You probably don't want to add all the handling logic for that, and besides, what if it's something you didn't expect? So just handle the exception if you can, re-raise it unless you're certain it's resolved, and gracefully handle it at a global level (e.g. Show a message like "Something went wrong, but you might be able to continue working. Detailed info: '[ex.Message]'. Abort or Retry?")

    HTH!

    John Saunders, thanks for the correction.

提交回复
热议问题