473,714 Members | 2,462 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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., ArgumentExcepti on accepts null arguments
without raising ArgumentNullExc eption. 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 ArgumentExcepti on (and not ArgumentNullExc eption even
though the argument is null):

throw new ArgumentExcepti on(null);

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

throw new ArgumentNullExc eption(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 StringEmptyExce ption and an empty
string is passed to the constructor of that exception, I would consider
raising the StringEmptyExce ption - or at least ArgumentExcepti on (or
perhaps some other exception, like a custom
"InternalString EmptyException" ).

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

Dec 6 '06 #1
3 3405
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 ArgumentNullExc eption, for
instance, and inadvertently catch an ArgumentNullExc eption 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., ArgumentExcepti on accepts null arguments
without raising ArgumentNullExc eption. 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 ArgumentExcepti on (and not ArgumentNullExc eption even
though the argument is null):

throw new ArgumentExcepti on(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.Argumen tException' 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 ArgumentNullExc eption(null);
If it were to have thrown an ArgumentNullExc eption, 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 ArgumentNullExc eption from a
constructor of the ArgumentNullExc eption 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 StringEmptyExce ption and an empty
string is passed to the constructor of that exception, I would consider
raising the StringEmptyExce ption - or at least ArgumentExcepti on (or
perhaps some other exception, like a custom
"InternalString EmptyException" ).

But, it seems that exceptions are meant to be very tolerant - and I
would prefer that they were not.
StringEmptyExce ption doesn't make sense. You should throw an
ArgumentExcepti on. For the sake of discussion, if you were to have a custom
StringEmptyExce ption class, its constructor might accept a parameter named,
"paramName" just like ArgumentExcepti on, for instance. In that case, if the
caller decides to pass null then the StringEmptyExce ption 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 ArgumentNullExc eption, then somebody
calling into a method or setting a property to an empty string might end up
getting an ArgumentNullExc eption, 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 ArgumentNullExc eption, for
instance, and inadvertently catch an ArgumentNullExc eption 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., ArgumentExcepti on accepts null arguments
without raising ArgumentNullExc eption. 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 ArgumentExcepti on (and not ArgumentNullExc eption even
though the argument is null):
throw new ArgumentExcepti on(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.Argumen tException' 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 ArgumentNullExc eption(null);If it were to have thrown an ArgumentNullExc eption, 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 ArgumentNullExc eption from a
constructor of the ArgumentNullExc eption 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 StringEmptyExce ption and an empty
string is passed to the constructor of that exception, I would consider
raising the StringEmptyExce ption - or at least ArgumentExcepti on (or
perhaps some other exception, like a custom
"InternalString EmptyException" ).
But, it seems that exceptions are meant to be very tolerant - and I
would prefer that they were not.StringEmpty Exception doesn't make sense. You should throw an
ArgumentExcepti on. For the sake of discussion, if you were to have a custom
StringEmptyExce ption class, its constructor might accept a parameter named,
"paramName" just like ArgumentExcepti on, for instance. In that case, if the
caller decides to pass null then the StringEmptyExce ption 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 ArgumentNullExc eption, then somebody
calling into a method or setting a property to an empty string might end up
getting an ArgumentNullExc eption, 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
9254
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 give invalid values for the property it is throwing System exception as follows. "Invalid Property Value. Is not a valid value for Int32. Though I have custom validation message in the Property set system throws exception before this.
11
8135
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
3733
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 all the messages to a message box (ShowMessageBox=true). The required field validation error messages show up in the summary just fine but I can't get the custom validation message to show up if invalid. So far I have the summary control...
9
2223
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) in page_load, or elsewhere, that says page.validate, no control says "causesvalidation=true", and the AutoEventWireup is set to false. So I would think that the control's server event function would NOT execute, but it does execute right after...
1
17043
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 control in my aspx page with two image buttons, one for an edit command, another a delete command. Here is a cut down code fragment. ...
1
1385
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 like to assume that the UI later will handle a lot of this but I cannot be 100% set on this as another developer may not expose all the validation rules if they make a new front end. Right now my data access layer uses checks within the procedures...
2
2175
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. -------------------------------------------------------------------------------- Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/in configuration or <%@ Page EnableEventValidation="true"...
3
2273
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 custom exception (ValidationException) The exception bubbles up to the UI where it gets trapped: Private Sub Page_Error(ByVal sender As Object, ByVal e As
9
4559
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
8803
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8711
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9175
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7953
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6636
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5948
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4464
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4726
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3158
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.