In our professor's example code he has one snippet that looks like this:
if (name == null || name == "")
throw new ArgumentException("name is null or empty");
And another snippet that looks like this:
if (!File.Exists(name))
{
throw new Exception("File does not exist!");
}
I was just wondering what the different was and why one is used above the other
Exception
is the base class for all exceptions. ArgumentException
is used to say that a parameter is not valid. It subclasses from Exception
. With catch
, you can actually filter base on the type of the exception and handle each one differently.
MSDN describes it well:
When you have to throw an exception, you can often use an existing exception type in the .NET Framework instead of implementing a custom exception. You should use a standard exception type under these two conditions:
- You are throwing an exception that is caused by a usage error (that is, by an error in program logic made by the developer who is calling your method). Typically, you would throw an exception such as ArgumentException, ArgumentNullException, InvalidOperationException, or NotSupportedException. The string you supply to the exception object's constructor when instantiating the exception object should describe the error so that the developer can fix it. For more information, see the Message property.
- You are handling an error that can be communicated to the caller with an existing .NET Framework exception. You should throw the most derived exception possible. For example, if a method requires an argument to be a valid member of an enumeration type, you should throw an InvalidEnumArgumentException (the most derived class) rather than an ArgumentException.