C#: Throwing Custom Exception Best Practices

前端 未结 8 948
没有蜡笔的小新
没有蜡笔的小新 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: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.

提交回复
热议问题