|
You've already asked this in C# forum. Please, do not post the same question in several forums.
|
|
|
|
|
sorry erik, i forgot to remove this post
modified on Tuesday, January 18, 2011 5:07 AM
|
|
|
|
|
Please go through this link:
This[^]
|
|
|
|
|
Hi,
I would like to get a few expert opinions on the question of when to define a custom exception.
According to some books I have read, the exceptions built into .NET should generally be reserved for .NET's own use and developers should create custom exceptions for classes they create. This seems to me to be unnecessary - and even undesirable - at times. For example, if I had a class with a function that had a single integer parameter that should always be in the range 0-9 and it receives 42, I would have thought the best exception to throw would be the predefined System.ArgumentOutOfRangeException; it seems to fit the bill perfectly.
If you were creating a whole code library, I can see the value of defining a custom set of exceptions for the library, but for individual lumps of code, it seems like overkill.
I would be very interested to hear other opinions on this subject or get links to good articles on this subject.
Best wishes, Patrick
|
|
|
|
|
Hmmm. I've never read anything to suggest that you shouldn't be able to use the standard exceptions. It's insane for somebody to suggest otherwise because they are effectively telling you that your code cannot act like the underlying framework. What do I mean by this?
Well, suppose that you have written a framework of your own that sits on top of the .NET framework (an MVVM framework for instance), and it gains popularity with other developers. Now, this framework checks parameters to ensure they aren't null - it's only natural for the end developer to expect that a null parameter would be raised via an ArgumentNullException - after all, he's making other calls that are throwing this exception.
Suppose now, that you've used some GPL in your library, and in this code, it also checks for null arguments and in certain places, your code is such a thin wrapper that you just pass the arguments that you've got across. All of a sudden, you've got two different types of custom ArgumentNullException to handle, and that's just plain stupid.
If you have an exception type that isn't catered for by the underlying framework then, by all means, create your own exception for it - I do this quite a lot (for instance, I have an UnexpectedStringFormatException exception that I sometimes raise when I have a regular expression test that fails). If it's something as simple as an argument out of range, then use the ArgumentOutOfRangeException because that's what it's there for.
|
|
|
|
|
The authors that you're referring to have heard about the rule-of-thumb that you should inherit your own exceptions, preferably not inheriting from ApplicationException . The reasoning is that it helps in differentiating between the exceptions that the framework throws and the exceptions that you app throws.
Not considering the fact that most shops create their own framework on top of .NET, and have multiple apps on that framework. According to their rule-of-thumb, the apps shouldn't re-use the exceptions from their own framework.
..now, if programming could be reduced to a few rule-of-thumbs, we'd all be using Visual Basic. By all means, throw an OutOfRangeException if that's what's occuring - the goal of an exception is handling an exceptional situation, and if OutOfRange describes that best, then that is the one that should be applied.
I are Troll
|
|
|
|
|
I like to create my own exceptions, except (no pun intended) for the most basic validations, because the situation you mentioned is a bit rare in business applications. The custom exception often adds semantic information. In a similar situation, NegativeDepositAmmountException IMHO could be much more meaningful than ArgumentOutOfRangeException. If your number has a strict domain, often is a class or some entity that needs special treatment.
Another similar case is where you can't receive a Customer with an empty or null Customer.Address field. What would you prefer to receive? A NullReferenceException or a EmptyAdressException?
It means a lot more manual work, but in the long run it pays when you deploy your code to your customers.
|
|
|
|
|
If you have NegativeDepositAmmountException inherit ArgumentOutOfRangeException you can have the best of both worlds. You can encode as much semantic information as you need, while simultaneously making it easy for a consumer to handle common error cases without having to learn all the details of your implementation up front.
3x12=36
2x12=24
1x12=12
0x12=18
|
|
|
|
|
It's a very nice idea, but not always practical, and could lead to some inconsistencies. I learned the hard way to take a lot of care when deriving a class, and follow more rigidly LSP (Liskov Substitution Principle).
In the same example, EmptyAdressException cannot be derived from NullReferenceException, in the same way a Square cannot be derived from a Rectangle.
|
|
|
|
|
I'm not following. If I understand LSP correctly it says that if I derive Square from Rectangle that Squares must have all the properties of a rectangle; which they do so the derivation should be allowed under LSP.
What am I missing?
3x12=36
2x12=24
1x12=12
0x12=18
|
|
|
|
|
That's what I thought at first, too. But LSP is not about properties, nor methods. LSP is about "substitution", and that is more closely related to an specialization. A Red Rectangle can be derived from a Rectangle, but a Square is much more an abstract class on its own.
The "is a" relationship of OO is flawed; you can read more about that on this pdf[^]
|
|
|
|
|
Also, a inherited class should only throw exceptions that the base class throws, or descendants thereof.
I are Troll
|
|
|
|
|
IMO, it really depends on what description the pre-defined .NET exception is offering. Is it enough for the user to understand what went wrong? If it isn't, then you should create your own exception and put in a custom name and message to let the user know exactly about the problem.
|
|
|
|
|
I would say you need to build your own exception set when you (your clients) don't like the exception set Microsoft is providing - as simple as that.
The funniest thing about this particular signature is that by the time you realise it doesn't say anything it's too late to stop reading it.
My latest tip/trick
|
|
|
|
|
If the condition that triggers the exception is reasonably generic (a null argument, or a value out of range), I use one of the predefined .NET exceptions. If the condition is domain-specific to the application, then I define my own.
For example, I have a class that handles TCP/IP socket communications between my application and a Windows service. This class can throw InvalidCastException s, given that our protocol includes data type information along with each data value in a message. This ensures that the sender/receiver on my end agrees with the receiver/sender on the other end. It also can throw BufferException or ReadSizeException , exceptions defined in the class derived from ApplicationException , that reflect protocol errors.
Patrick Skelton wrote: According to some books I have read, the exceptions built into .NET should generally be reserved for .NET's own use and developers should create custom exceptions for classes they create.
This is symptomatic of an 'anti-pattern' you see occasionally. Some programmers think that they always have to insulate their applications from potential changes to the framework they're using. They build wrapper classes for everything. The wrappers end up being extremely thin layers on top of the actual framework. All they accomplish with this is to obfuscate their use of the framework. This makes their code more difficult to debug and maintain, since they rarely document framework considerations and constraints that their wrapper promotes.
Software Zen: delete this;
|
|
|
|
|
I try to handle an exception-causing code to avoid throwing an exception, and let the code fail gracefully (not necessarily terminating a process or action, but using reasonable properties to allow it to continue.
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass." - Dale Earnhardt, 1997
|
|
|
|
|
Yeah, it depends on the situation. I use the built-in Exceptions when they seem appropriate and define my own when I want to add more information. As with Exceptions raised by ADO.net code -- I can throw problem-specific Exceptions (duplicate, referential integrity, etc.) that also include the text of the statement and any parameters involved so they can be handled appropriately by the application.
Also, if you do define your own Exception, derive it from the appropriate base Exception -- your own OutOfRange should derive from the base OutOfRange.
|
|
|
|
|
I'll agreed with the other recommendations also. First, try to prevent the exception in the first place but we all know that is not possible or desirable in some situation. If the exception fits a built-in type, ArgumentNullException for instance then by all means use it. However, if you need to differentiate or have a custom case then certainly creating your own is valid.
I know the language. I've read a book. - _Madmatt
|
|
|
|
|
I generally just do this instead of creating custom exception objects:
catch (Exception ex)
{
throw new Exception("My custom exception message", ex);
}
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass." - Dale Earnhardt, 1997
|
|
|
|
|
Yes but there are times when it is advantageousness to differentiate between a custom exception
try
{
Foo();
}
catch(UserIsMoronException ex)
{
BeatSensless();
}
catch(Exception ex)
{
Log();
}
I know the language. I've read a book. - _Madmatt
|
|
|
|
|
Mark Nischalke wrote: catch(UserIsMoronException ex)
They REALLY need to add this one to the framework.
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass." - Dale Earnhardt, 1997
|
|
|
|
|
John Simmons / outlaw programmer wrote: Mark Nischalke wrote:
catch(UserIsMoronException ex)
They REALLY need to add this one to the framework.
They did, and 85% of the exceptions where caught by, ... you guessed it right...
|
|
|
|
|
Having a type-safe object has some advantages over a string.
It's harder to filter if you're examining a string, and I like having a class that describes the problem and being able to catch and handle that specific case. Or worse- let the user decide whether or not those kind of exceptions need be logged (like file-access errors for the sysadmin, common networkexceptions for the networkadmin, and whether the user allows the app to send unhandled exceptions with a stacktrace back home) There's a string in the custom exception of course, along with placeholders for values to help diagnose the problem. But in code, I can act on the object itself, and I don't need to depend on the formatting of a string.
It's a matter of preference, I guess, as you can accomplish the same visual and functional endresult.
No, the worst kind of exceptions are translated ones. Yes, I know about the unlocalize website, but that's not exactly convenient. I'm hoping that I can rectify some by removing the .NET language packs from my PC.
I are Troll
|
|
|
|
|
John Simmons / outlaw programmer wrote: I generally just do this instead of creating custom exception objects:
catch (Exception ex)
{
throw new Exception("My custom exception message", ex);
}
I believe that is a mistake. I discuss this on my article[^], more deeply but there are 3 main problems with this approach:
1. Internationalization: when you need to catch your exception you'll need to have some sort of switch on the text message. With i18n, which message should you use on the switch?
2. You'll force your users to catch (Exception ex), which is a too broad class and they'll need to handle a lot of other different exceptions.
3. You'l force your users to stop using the more efficient catch (XXXXException) and use a switch instead, which is both less readable and less efficient.
|
|
|
|
|
The well designed application doesn’t needs exceptions!
In a more serious note, the only case I create custom exceptions is when I’m dealing with COM objects and/or native libraries in order to wrap their error handling and error messages. In any other cases the build-in exceptions and re-throwing them in some cases seems to be enough for me.
There is only one Ashley Judd and Salma Hayek is her prophet!
Advertise here – minimum three posts per day are guaranteed.
|
|
|
|
|