If I have a method that checks the validity of its arguments, is it ok to throw my own custom exceptions derived from System.ArgumentException
? I am asking because ArgumentException
is itself derived from System.SystemException
and I am seeing conflicting guidelines as to whether an application should derive from SystemException
. (Albeit indirectly, deriving from ArgumentException
is still tantamount to deriving from SystemException
.)
I see lots of guidelines saying don't derive from ApplicationException
, but derive from Exception instead. I'm happy with that. What I'm not sure about is whether it's ok to derive from SystemException too.
If I shouldn't derive from SystemException
, then what should I derive my "invalid argument"
exception classes from?
ArgumentException is thrown when a method is invoked and at least one of the passed arguments does not meet the parameter specification of the called method. The ParamName property identifies the invalid argument.
To prevent the error, instantiate the object. An object returned from a method call is then passed as an argument to a second method, but the value of the original returned object is null . To prevent the error, check for a return value that is null and call the second method only if the return value is not null .
The MSDN page about Best Practices for Handling Exceptions says
Throw an ArgumentException or a class derived from ArgumentException if invalid parameters are passed.
So i would say it's ok and even recommended.
One benefit of deriving from System.ArgumentException is that catch(System.ArgumentException)
blocks will be able to handle your custom exception type as well as System.ArgumentException
. This may or may not be what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With