473,387 Members | 1,582 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Argument validation within custom exception

This is a long one, so I'll summarize:

1. What are your opinions on raising an exception within the
constructor of a (custom) exception?

2. How do -you- validate arguments in your own exception constructors?

I've noticed that, f.ex., ArgumentException accepts null arguments
without raising ArgumentNullException. Obviously, if nothing is to be
supplied to the exception constructor, the default constructor should
be called. What are your opinions on that type of error tolerance
within exception constructors?

- This will raise ArgumentException (and not ArgumentNullException even
though the argument is null):

throw new ArgumentException(null);

- Without a stack trace, I suppose the following would be tricky to
debug if argument validation raised exceptions within exception
constructors:

throw new ArgumentNullException(null);
What if I really want my custom exception to require that an empty
string may not be passed to the constructor? Let's say that I really
regard passing an empty string to the exception constructor as an
error, which would leave the exception in an erroneous state if it were
to be allowed...

If I have a custom exception called StringEmptyException and an empty
string is passed to the constructor of that exception, I would consider
raising the StringEmptyException - or at least ArgumentException (or
perhaps some other exception, like a custom
"InternalStringEmptyException").

But, it seems that exceptions are meant to be very tolerant - and I
would prefer that they were not.

Dec 6 '06 #1
3 3380
Hi,
This is a long one, so I'll summarize:

1. What are your opinions on raising an exception within the
constructor of a (custom) exception?
It seems unnecessary to me. Exceptions should provide information, not
validation. It shouldn't matter whether arguments are incorrect - that's
the caller's problem, IMO. Also, exceptions shouldn't depend on external
state either, so there should be no reason to throw exceptions at all from
within an exception's constructor.

If exceptions could be thrown, then all calling code would have to validate
arguments before passing them to Exception constructors. A bug in code that
doesn't validate the arguments correctly will not be easy to debug since a
caller might add a try..catch to catch some ArgumentNullException, for
instance, and inadvertently catch an ArgumentNullException from the buggy
method in which it called. There would be no way of knowing what the "real"
exception was going to be, especially if the exception is simply suppressed.
I've just posted a blog entry related to this topic that you might want to
look at (link after my sig).

Microsoft doesn't seem to provide any guidance on this topic, however.

"Designing Custom Exceptions"
http://msdn2.microsoft.com/en-us/library/ms229064.aspx
2. How do -you- validate arguments in your own exception constructors?
It's extremely rare that I create a custom exception, and when I do it's
always part of library code. I never throw an exception for invalid
arguments from within an exception's constructor, and I only consider an
argument to be invalid at all when it's null and I require a non-null
reference. In that case, I'll do something like: (arg == null) ?
string.Empty : arg.ToString(). In other words, use a default value.
I've noticed that, f.ex., ArgumentException accepts null arguments
without raising ArgumentNullException. Obviously, if nothing is to be
supplied to the exception constructor, the default constructor should
be called. What are your opinions on that type of error tolerance
within exception constructors?

- This will raise ArgumentException (and not ArgumentNullException even
though the argument is null):

throw new ArgumentException(null);
Here you're just setting the message parameter to null. In this case the
default message will be used by the exception class: "Exception of type
'System.ArgumentException' was thrown".
- Without a stack trace, I suppose the following would be tricky to
debug if argument validation raised exceptions within exception
constructors:

throw new ArgumentNullException(null);
If it were to have thrown an ArgumentNullException, the stack trace would
have provided that information. It wouldn't be obvious, however, and that's
why it doesn't make sense to throw an ArgumentNullException from a
constructor of the ArgumentNullException class itself.
What if I really want my custom exception to require that an empty
string may not be passed to the constructor? Let's say that I really
regard passing an empty string to the exception constructor as an
error, which would leave the exception in an erroneous state if it were
to be allowed...

If I have a custom exception called StringEmptyException and an empty
string is passed to the constructor of that exception, I would consider
raising the StringEmptyException - or at least ArgumentException (or
perhaps some other exception, like a custom
"InternalStringEmptyException").

But, it seems that exceptions are meant to be very tolerant - and I
would prefer that they were not.
StringEmptyException doesn't make sense. You should throw an
ArgumentException. For the sake of discussion, if you were to have a custom
StringEmptyException class, its constructor might accept a parameter named,
"paramName" just like ArgumentException, for instance. In that case, if the
caller decides to pass null then the StringEmptyException class itself can
proceed as normal since it doesn't actually require that argument to have a
non-null value - it's not using it for any particular processing logic. If
it did, and you tried to throw an ArgumentNullException, then somebody
calling into a method or setting a property to an empty string might end up
getting an ArgumentNullException, not realizing that that exception wasn't
intended to be thrown, and probably wasn't documented either since it's
really a bug. Very misleading.

--
Dave Sexton
http://davesexton.com/cs/blogs/blog/...ntingency.aspx
Dec 6 '06 #2
Thanks for taking the time!

I suppose a solution could be to use Debug.Assert to validate arguments
in some areas (since the caller is YOU (and often *only* you), and you
like working code, all arguments should validate properly, right?).

So, finally, I've come to the conclusion not to raise exceptions within
exception constructors!

However, I usually do that when it comes to argument validation in
methods as I really believe that passing invalid data to methods is an
exceptional error. In most cases.

Thx again!

On Dec 6, 10:30 am, "Dave Sexton" <dave@jwa[remove.this]online.com>
wrote:
Hi,
This is a long one, so I'll summarize:
1. What are your opinions on raising an exception within the
constructor of a (custom) exception?It seems unnecessary to me. Exceptions should provide information, not
validation. It shouldn't matter whether arguments are incorrect - that's
the caller's problem, IMO. Also, exceptions shouldn't depend on external
state either, so there should be no reason to throw exceptions at all from
within an exception's constructor.

If exceptions could be thrown, then all calling code would have to validate
arguments before passing them to Exception constructors. A bug in code that
doesn't validate the arguments correctly will not be easy to debug since a
caller might add a try..catch to catch some ArgumentNullException, for
instance, and inadvertently catch an ArgumentNullException from the buggy
method in which it called. There would be no way of knowing what the "real"
exception was going to be, especially if the exception is simply suppressed.
I've just posted a blog entry related to this topic that you might want to
look at (link after my sig).

Microsoft doesn't seem to provide any guidance on this topic, however.

"Designing Custom Exceptions"http://msdn2.microsoft.com/en-us/library/ms229064.aspx
2. How do -you- validate arguments in your own exception constructors?It's extremely rare that I create a custom exception, and when I do it's
always part of library code. I never throw an exception for invalid
arguments from within an exception's constructor, and I only consider an
argument to be invalid at all when it's null and I require a non-null
reference. In that case, I'll do something like: (arg == null) ?
string.Empty : arg.ToString(). In other words, use a default value.
I've noticed that, f.ex., ArgumentException accepts null arguments
without raising ArgumentNullException. Obviously, if nothing is to be
supplied to the exception constructor, the default constructor should
be called. What are your opinions on that type of error tolerance
within exception constructors?
- This will raise ArgumentException (and not ArgumentNullException even
though the argument is null):
throw new ArgumentException(null);Here you're just setting the message parameter to null. In this case the
default message will be used by the exception class: "Exception of type
'System.ArgumentException' was thrown".
- Without a stack trace, I suppose the following would be tricky to
debug if argument validation raised exceptions within exception
constructors:
throw new ArgumentNullException(null);If it were to have thrown an ArgumentNullException, the stack trace would
have provided that information. It wouldn't be obvious, however, and that's
why it doesn't make sense to throw an ArgumentNullException from a
constructor of the ArgumentNullException class itself.
What if I really want my custom exception to require that an empty
string may not be passed to the constructor? Let's say that I really
regard passing an empty string to the exception constructor as an
error, which would leave the exception in an erroneous state if it were
to be allowed...
If I have a custom exception called StringEmptyException and an empty
string is passed to the constructor of that exception, I would consider
raising the StringEmptyException - or at least ArgumentException (or
perhaps some other exception, like a custom
"InternalStringEmptyException").
But, it seems that exceptions are meant to be very tolerant - and I
would prefer that they were not.StringEmptyException doesn't make sense. You should throw an
ArgumentException. For the sake of discussion, if you were to have a custom
StringEmptyException class, its constructor might accept a parameter named,
"paramName" just like ArgumentException, for instance. In that case, if the
caller decides to pass null then the StringEmptyException class itself can
proceed as normal since it doesn't actually require that argument to have a
non-null value - it's not using it for any particular processing logic. If
it did, and you tried to throw an ArgumentNullException, then somebody
calling into a method or setting a property to an empty string might end up
getting an ArgumentNullException, not realizing that that exception wasn't
intended to be thrown, and probably wasn't documented either since it's
really a bug. Very misleading.

--
Dave Sextonhttp://davesexton.com/cs/blogs/blog/archive/2006/12/05/Handling-Excep...
Dec 7 '06 #3
Hi,
I suppose a solution could be to use Debug.Assert to validate arguments
in some areas (since the caller is YOU (and often *only* you), and you
like working code, all arguments should validate properly, right?).
Yes, that's not a bad idea for testing purposes. I think our perception of
exceptions differ from one another though. I see them as a container for
information. At the time of an exception, you'll want to see as much
available and applicable information as possible, so you commonly choose the
Type of exception that is appropriate and then supply the appropriate
arguments that your code has in scope. Any invalid information from the POV
of the caller should simply be considered as missing from the POV of the
exception, since its only job is to collect any information that is
available. That's why I feel that exceptions being thrown from within
exceptions doesn't make sense, regardless of any problems it may cause such
as the ones we've discussed already.
So, finally, I've come to the conclusion not to raise exceptions within
exception constructors!
:)
However, I usually do that when it comes to argument validation in
methods as I really believe that passing invalid data to methods is an
exceptional error. In most cases.
I completely agree. I think it's better to validate all method arguments,
unless your method doesn't depend on the state of the argument, such as when
a method simply forwards one argument to another method call.

--
Dave Sexton
Dec 7 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Shanthi | last post by:
I am using property grid in C# application. Property grid displays the propeties properly. But I have some problem in displaying custom validation message. I have integer type property. When I...
11
by: Diego | last post by:
Hi all a quick question: how can I validate a date in asp.net (2.0) with c#? I didn't find a quick anwer. Thanks, Diego.
2
by: Barbara Alderton | last post by:
I setup some standard Required Field Validation controls and one Custom validation control on an ASP.NET page (within a user control) to validate text entry. I also setup a Summary Control to post...
9
by: AFN | last post by:
I was just dropped into someone else's code (isn't that always so fun?). I can't figure out why a custom validation control's server event function is executing. There is nothing (that I see)...
1
by: Timbo | last post by:
Hi all, This is my first message here so i'll try and include all the information that will help you help me out, if possible. Basically I am using C# in ASP.NET 2.0 and have a Repeater...
1
by: Nick | last post by:
I was wondering other opinions on this topic... I am working on an n-tier application which may be broken out to different servers at a later date. How should I go about the validation? I would...
2
by: Nathan Sokalski | last post by:
I have a DataList in which the ItemTemplate contains two Button controls that use EventBubbling. When I click either of them I receive the following error: Server Error in '/' Application....
3
by: hardieca | last post by:
Hi, I've created an n-tier app where validation rules reside in the business layer. When a webform is saved, a business object examines its state, and if some property is invalid, throws a...
9
by: 200dogz | last post by:
Hi guys, I want to have a button which opens up a new window when pressed. <asp:Button ID="Button1" runat="server" Text="Open new window" /> ... Button1.Attributes.Add("OnClick",
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.