C#: Throwing Custom Exception Best Practices

前端 未结 8 916
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 01:25

I have read a few of the other questions regarding C# Exception Handling Practices but none seem to ask what I am looking for.

If I implement my own custom Exception

相关标签:
8条回答
  • 2020-11-30 02:25

    The most important thing for code to know when catching an exception, which is unfortunately completely missing from the Exception object, is the state of the system relative to what it "should" be (presumably the exception was thrown because there was something wrong). If an error occurs in a LoadDocument method, presumably the document didn't load successfully, but there are at least two possible system states:

    1. The system state may be as though the load were never attempted. In this case, it would be entirely proper for the application to continue if it can do so without the loaded document.
    2. The system state may be sufficiently corrupted that the best course of action would be to save what can be saved to 'recovery' files (avoid replace the user's good files with possibly-corrupt data) and shut down.

    Obviously there will often be other possible states between those extremes. I would suggest that one should endeavor to have a custom exception which explicitly indicates that state #1 exists, and possibly one for #2 if foreseeable but unavoidable circumstances may cause it. Any exceptions which occur and will result in state #1 should be wrapped in an exception object indicating state #1. If exceptions can occur in such a fashion that the system state might be compromised, they should either be wrapped as #2 or allowed to percolate.

    0 讨论(0)
  • 2020-11-30 02:30

    Based on my experience with libraries, you should wrap everything (that you can anticipate) in a FooException for a few reasons:

    1. People know it came from your classes, or at least, their usage of them. If they see FileNotFoundException they may be looking all over for it. You're helping them narrow it down. (I realize now that the stack trace serves this purpose, so maybe you can ignore this point.)

    2. You can provide more context. Wrapping an FNF with your own exception, you can say "I was trying to load this file for this purpose, and couldn't find it. This hints at possible correct solutions.

    3. Your library can handle cleanup correctly. If you let the exception bubble, you're forcing the user to clean up. If you've correctly encapsulated what you were doing, then they have no clue how to handle the situation!

    Remember to only wrap the exceptions you can anticipate, like FileNotFound. Don't just wrap Exception and hope for the best.

    0 讨论(0)
提交回复
热议问题