简体   繁体   中英

Good practice of exception hierarchy in C#

Now I write C# code after the PHP.

In PHP I create a hierarchy of exceptions guided by the recommendations of the Zend Framework(Symfony now use something similar).

In package(for example Order) I create folder Exception, in this folder(translate from php to C#):

namespace Order.Exception
{
    interface ExceptionInterface{}
    class ApplicationException : System.ApplicationException, ExceptionInterface{}
    class OrderNotFoundException : ApplicationException {}
    class SomethingHappensException : ApplicationException{}
}

I need a lot of exceptions(relatively) to conveniently express the things from domain.

Is there any have good practices to create hierarchies of exceptions?

Technical details of creation I understand completely. The issue of good practice.

Two quotes from CLR via C#, 4th Edition :

If you want to define an exception type hierarchy, it is highly recommended that the hierarchy be shallow and wide in order to create as few base classes as possible. The reason is that base classes act as a way of treating lots of errors as one error, and this is usually dangerous.

(...)

There are versioning ramifications here, too. If you define a new exception type derived from an existing exception type, then all code that catches the existing base type will now catch your new type as well. In some scenarios, this may be desired and in some scenarios, it may not be desired. The problem is that it really depends on how code that catches the base class responds to the exception type and types derived from it. Code that never anticipated the new exception may now behave unpredictably and open security holes. The person defining the new exception type can't know about all the places where the base exception is caught and how it is handled. And so, in practice, it is impossible to make a good intelligent decision here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM