Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ApplicationException or create custom exceptions?

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?

like image 556
Dave New Avatar asked May 17 '13 06:05

Dave New


People also ask

Should I create custom exceptions?

You should only implement a custom exception if it provides a benefit compared to Java's standard exceptions. The class name of your exception should end with Exception. If an API method specifies an exception, the exception class becomes part of the API, and you need to document it.

Should I use ApplicationException?

You should not throw an ApplicationException exception in your code, and you should not catch an ApplicationException exception unless you intend to re-throw the original exception.

What is the advantage of creating your own custom exception class?

The big advantage is that it allows you to throw and exceptions that mean what you want them to mean. If you reuse an existing exception, any piece of your code that catches the exception has to deal with possibility that the actual exception wasn't thrown by your code, but by some other library party code.


2 Answers

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.

like image 61
Damien_The_Unbeliever Avatar answered Nov 15 '22 14:11

Damien_The_Unbeliever


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)
{
}
like image 20
Tieson T. Avatar answered Nov 15 '22 14:11

Tieson T.