What factors should be taken into consideration when writing a custom exception class?

后端 未结 7 929
甜味超标
甜味超标 2020-12-29 15:38

When are custom Exception classes most-valuable?
Are there cases when they should or should not be used? What are the benefits?

Related

7条回答
  •  -上瘾入骨i
    2020-12-29 16:13

    I think the simple answer is "Create a custom exception when no existing exception adequetely expresses the exceptional situation."

    I also have a second rule that I apply: "Only create a custom exception if you expect a developer to be able to handle the exception." There is no point in creating a new exception if you don't consider the exception a recoverable condition. It is more effectient to throw InvalidOperationException in that context.

    EDIT: Ended up writing a blog post on this subject: http://blogs.msdn.com/jaredpar/archive/2008/10/20/custom-exceptions-when-should-you-create-them.aspx

提交回复
热议问题