Here’s a list of common .NET exceptions you can throw when necessary. You should not create your own exception classes when an existing class will do.
-
RSS Links
Categories
-
Recent Comments
- Craig Stuntz’s Weblog : The Strange Story of Erlang’s Success on "Let It Crash" Programming
- Craig Stuntz’s Weblog : Lightweight Frameworks, Again on Lightweight Frameworks
- Craig Stuntz on LINQ to SQL : Entity Framework :: WinForms : WPF
- tcmaster on LINQ to SQL : Entity Framework :: WinForms : WPF
- Giel on My CodeRage Presentation: Functional Programming in Delphi 2009
-
{ 4 } Comments
Why not subclass these. Then I can tell mine from the system generated ones.
Why would I raise a system exception?
You should only create an exception class (including subclasses of these) when you have a need for it. In other words, you (or a developer using your assembly) will be catching the exception somewhere, or you need to attach new properties to the exception.
You can tell when an exception is "yours" by looking at the call stack. You don’t need to subclass to get this info.
The reason to raise a system exception is that other developers will know how to handle them. If you write a method and need to throw when a parameter is null/nil, you can throw either your own exception or System.ArgumentNullException. If you throw the latter (System.ArgumentNullException) then anyone who has written a global exception handler will already deal with this correctly. If you create your own exception class, you have added no information and you may be requiring folks using your code to do extra work.
Creating a duplicate exception class, in other words, is more or less analogous to copying code with cut and paste instead of encapsulating common operations in a single method.
> You can tell when an exception is "yours" by looking at the call stack. You don’t need to subclass to get this info.
"Need" may be stretching it, but it certainly is more convenient than writing code to look at and interpret the call stack.
>The reason to raise a system exception is that other developers will know how to handle them. If you write a method and need to throw when a parameter is null/nil, you can throw either your own exception or System.ArgumentNullException. If you throw the latter (System.ArgumentNullException) then anyone who has written a global exception handler will already deal with this correctly. If you create your own exception class, you have added no information and you may be requiring folks using your code to do extra work.
I don’t know what you are talking about Craig. If I subclass ANE, then any exception handler should handle it transparently. Where is the extra work?
I don’t think subclassing ArgumentNullException is a terrible thing, if you feel you have a need for it. I would have a problem with creating a sibling class. I wouldn’t do it myself for the reasons I stated, though.
Post a Comment