Why Create Custom Exceptions? [closed]

Why do we need to create custom exceptions in .NET?


Solution 1:

Specific customs exceptions allow you to segregate different error types for your catch statements. The common construct for exception handling is this:

try
{}
catch (Exception ex)
{}

This catches all exceptions regardless of type. However, if you have custom exceptions, you can have separate handlers for each type:

try
{}
catch (CustomException1 ex1)
{
    //handle CustomException1 type errors here
}
catch (CustomException2 ex2)
{
    //handle CustomException2 type errors here
}
catch (Exception ex)
{
    //handle all other types of exceptions here
}

Ergo, specific exceptions allow you a finer level of control over your exception handling. This benefit is shared not only by custom exceptions, but all other exception types in the .NET system libraries as well.

Solution 2:

I did a lengthy blog post on this subject recently:

http://blogs.msdn.com/jaredpar/archive/2008/10/20/custom-exceptions-when-should-you-create-them.aspx

The crux of it comes down to: Only create a custom exception if one of the following are true

  1. You actually expect someone to handle it.
  2. You want to log information about a particular error

Solution 3:

So you can also throw them yourself, and then catch them and know exactly what they mean.

Also: if you're building a class library/framework/api, it's often useful to create a BaseException that other exceptions in your code inherit from. Then when your code raises exceptions the programmers who are using it can quickly know the source of the exception.