Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to derive from System.ArgumentException?

Tags:

c#

exception

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?

like image 324
Klitos Kyriacou Avatar asked Oct 12 '12 11:10

Klitos Kyriacou


People also ask

When should you throw an ArgumentException?

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.

How do you handle Argumentnullexception in C#?

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 .


2 Answers

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.

like image 122
Botz3000 Avatar answered Oct 06 '22 14:10

Botz3000


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.

like image 23
dbattaglia Avatar answered Oct 06 '22 15:10

dbattaglia