Catching specific vs. generic exceptions in c#

后端 未结 7 1328
刺人心
刺人心 2020-12-08 06:16

This question comes from a code analysis run against an object I\'ve created. The analysis says that I should catch a more specific exception type than just the basic Except

相关标签:
7条回答
  • 2020-12-08 06:44

    Have a look at this article by Krzysztof Cwalina, which I've found very helpful in understanding when to catch or ignore exceptions:

    How to Design Exception Hierarchies

    All the principles it describes about designing exception hierarchies are also applicable when deciding when to catch, throw, or ignore exceptions. He divides exceptions into three groups:

    • Usage errors, such as DivideByZeroException, which indicate errors in code; you shouldn't handle these because they can be avoided by changing your code.
    • Logical errors, such as FileNotFoundException, which you need to handle because you can't guarantee they won't happen. (Even if you check for the file's existence, it could still be deleted in that split-second before you read from it.)
    • System failures, such as OutOfMemoryException, which you can't avoid or handle.
    0 讨论(0)
提交回复
热议问题