8

In my file repository, I will throw the following exceptions when the InsertFile() method is called:

  • When the upload file size limit is exceeded
  • When the storage capacity is exceeded

At the moment I am just throwing an ApplicationException with the relevant message:

public void InsertFile(HttpPostedFile uploadedFile)
{
    if (uploadedFile.ContentLength > FileSizeLimit)
    {
        throw new ApplicationException("File size limit exceeded.");
    }

    if (uploadedFile.ContentLength + FileStorageUsage > FileStorageCapacity)
    {
        throw new ApplicationException("File storage capacity exceeded.");
    }

    // ...
}

Questions:

Are there better exception classes that I should be using here?

Or should I be creating my own custom exceptions by deriving from ApplicationException?

Dave New
  • 38,496
  • 59
  • 215
  • 394

4 Answers4

8

Maybe read the documentation:

If you are designing an application that needs to create its own exceptions, you are advised to derive custom exceptions from the Exception class. It was originally thought that custom exceptions should derive from the ApplicationException class; however in practice this has not been found to add significant value.

As to whether there are better exceptions to throw - some might consider throwing an ArgumentOutOfRangeException if you don't want to define your own exception.

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
  • Thanks for the heads up on `ApplicationException`. `ArgumentOutOfRangeException` does sound appropriate: _"The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method."_ – Dave New May 17 '13 at 07:01
  • [This answer](http://stackoverflow.com/a/32854414/1497596) also cites the documentation for [ApplicationException](https://msdn.microsoft.com/en-us/library/System.ApplicationException) and provides similar (and updated) guidance. – DavidRR Jul 12 '16 at 14:45
3

Suppose it depends on how you plan on handling exceptions. Throwing specific exceptions lets you respond to them, um, specifically. For instance:

try
{
}
catch(FileSizeExceededException ex)
{
}
catch(StorageCapacityExceededException ex)
{
}
Tieson T.
  • 20,774
  • 6
  • 77
  • 92
  • In the client code, there would be checks, such as `IsFileSizeExceeded()`, so I wouldn't necessarily need to handle specific exceptions in order to send back feedback to the user. I will just need to log them. – Dave New May 17 '13 at 06:56
3

I would use an ArgumentException and an InvalidOperationException, respectively.

Tim
  • 5,435
  • 7
  • 42
  • 62
JeffRSon
  • 10,404
  • 4
  • 26
  • 51
1

Well what you have so far is alright, but I'd personally throw a System.ArgumentException (with a detailed message) instead.

Dimitar Dimitrov
  • 14,868
  • 8
  • 51
  • 79