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

后端 未结 7 942
甜味超标
甜味超标 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条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-29 16:17

    When you need to distinguish one exception from the others somehow. That's it, really. Of course, you could create an exception class that takes an enum to distinguish its cause, also.

    This is really easy to see when you want to pass extra information with the exception. The only reason to pass that information is if you want to be able to get that information later, and so you'll want to know the type so you can retrieve the information from that type and not others.

    In C++, and perhaps some other languages, you might also typedef an exception. This would allow for type distinguishing, and possibly future conversion to a custom class.

提交回复
热议问题