Should I catch and wrap general Exception?

前端 未结 14 1123
一向
一向 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:59

    There's an excellent blog post by Eric Lippert, "Vexing exceptions". Eric answers your question with some universal guidelines. Here is a quote from the "sum up" part:

    • Don’t catch fatal exceptions; nothing you can do about them anyway, and trying to generally makes it worse.
    • Fix your code so that it never triggers a boneheaded exception – an "index out of range" exception should never happen in production code.
    • Avoid vexing exceptions whenever possible by calling the “Try” versions of those vexing methods that throw in non-exceptional circumstances. If you cannot avoid calling a vexing method, catch its vexing exceptions.
    • Always handle exceptions that indicate unexpected exogenous conditions; generally it is not worthwhile or practical to anticipate every possible failure. Just try the operation and be prepared to handle the exception.

提交回复
热议问题