M
matko
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.
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.