Why Create Custom Exceptions?

C#.NetException

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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 - C#

I did a lengthy blog post on this subject recently:

https://docs.microsoft.com/en-us/archive/blogs/jaredpar/custom-exceptions-when-should-you-create-them

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 - C#

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.

Solution 4 - C#

Because it can make your intentions clear, and you can also track usages using IDE functionality. Say that you have a custom backend system called "FooBar" and you make a "FooBarDownException", you can track usages of this exception to identify any custom logic your application contains because FooBar is down. You can choose to catch this specific type of exception and ignore others, avoiding overloads and conditional logic within exception handlers. It's really just another version of strong typing. It also means you can avoid comments in your code because the exception has an intention revealing name.

Solution 5 - C#

I am not sure why "technically" but lets say I have a app/website that uses permissions. If someone does not have the right permission, its kinda stupid to throw a DivideByZero Exception or IOException. Instead I can create my AccessDeniedException which will help me debug later on.

Solution 6 - C#

It's the same reason you would create different exit codes for a non-.NET application: to specify different application-specific errors. Like...ConnectionBrokenException or um...UserSmellsBadException...or something.

This way you can know exactly what went wrong and act appropriately. For example, if you try to send some data and the data transport class throws a ConnectionBrokenException, you can pop up a reconnect dialog and try to reconnect. Then the reconnect method would throw a ConnectionTimeoutException if it times out, and you can again act appropriately.

Solution 7 - C#

Another reason, when a client talks to interfaces. Since the client is unaware of the implementations of the interface and since they maybe can throw different exceptions, it's good place to create custom exceptions to uniformise the errors thrown.

I wrote about this special case:

http://blog.mikecouturier.com/2010/01/creating-custom-exceptions-in-net-right.html

Solution 8 - C#

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

In addition, you can add specific info about the problem in order to let your exception handler act more accurately.

Solution 9 - C#

The standard .NET exceptions don't cover everything bad that can go wrong in any application nor are they intended to. Unless your program is very simple, it's likely you will have to create at least a few custom exceptions.

Solution 10 - C#

For one thing, Exceptions are implemented in the Library, not in the language--how can they create exceptions in the library? I'm pretty sure you aren't advocating that system libraries should have a different set of rules.

For another, it's actually possible to use an object tree of exceptions. Your inherited exceptions can have special attributes if you like--they can be used for more complicated things than they are. I'm not advocating they be used as a generic data transport mechanism or anything (although they could be), but I could see a case where someone implemented a custom logging solution that required a special attribute on the Exception...

Your custom exceptions could contain a flag indicating special treatment (maybe one saying you should restart the JVM), they could contain information about logging levels, a bunch of stuff.

Anyway, I'm not advocating this stuff, I'm just saying it's possible. The first paragraph is you real answer.

Solution 11 - C#

You shouldn't if the built in Exceptions appropriately describes the problem/exception. I wouldn't make my own base classes to create a custom ArgumentException, ArgumentNullException or InvalidOperationException.

You can create your own exceptions, and describe the error at a higher level. however, this usually doesn't help that much in debugging from a consumer class.

If you throw and catch the exception yourself, a custom exception may be in order.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYoann. BView Question on Stackoverflow
Solution 1 - C#Jon LimjapView Answer on Stackoverflow
Solution 2 - C#JaredParView Answer on Stackoverflow
Solution 3 - C#Joel CoehoornView Answer on Stackoverflow
Solution 4 - C#krosenvoldView Answer on Stackoverflow
Solution 5 - C#masfenixView Answer on Stackoverflow
Solution 6 - C#lc.View Answer on Stackoverflow
Solution 7 - C#Mike Gleason jr CouturierView Answer on Stackoverflow
Solution 8 - C#Serge WautierView Answer on Stackoverflow
Solution 9 - C#mhenry1384View Answer on Stackoverflow
Solution 10 - C#Bill KView Answer on Stackoverflow
Solution 11 - C#Øyvind SkaarView Answer on Stackoverflow