Why Create Custom Exceptions? [closed]
Asked Answered
G

11

57

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

Glogau answered 6/1, 2009 at 17:26 Comment(1)
As an aid to possibly reopening this question, from How to: Create User-Defined Exceptions on MSDN: "If you want users to be able to programmatically distinguish between some error conditions, you can create your own user-defined exceptions."Lyman
P
59

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.

Pattani answered 6/1, 2009 at 17:34 Comment(0)
N
41

I did a lengthy blog post on this subject recently:

https://learn.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
Nahama answered 6/1, 2009 at 17:33 Comment(0)
S
19

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.

Sikkim answered 6/1, 2009 at 17:28 Comment(0)
E
12

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.

Evaleen answered 6/1, 2009 at 17:29 Comment(3)
I wouldn't say that IDE functionality is the selling point, but making one's intentions clear is the most important reason.Maharajah
IMHO strong typing makes it possible to really work with code and make it better, an enabler for continious refactoring. So tooling is important.Evaleen
What does it mean by making intentions clear? I can see about the track usages, as this will find all areas which may be effected because FooBar is down (a standard exception type being used, such as ArgumentException, in so many different cases would not offer this benefit).Externality
C
3

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.

Countenance answered 6/1, 2009 at 17:28 Comment(0)
R
3

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.

Remains answered 6/1, 2009 at 17:31 Comment(0)
D
3

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

Dispatch answered 23/3, 2011 at 4:24 Comment(2)
I dislike the use of InvalidOperationException (or, for that matter, most Framework exceptions) for conditions from which a caller might try to handle and recover. The problem is that even if the method is documented as throwing an InvalidOperationException in some known system state, it's also possible that some internally-called method might throw InvalidOperationException when the system state is corrupt. It's too bad that none of the .net languages or Java allow exceptions to be declared as 'checked' <i>at the throw site</i>, with the semantics that one could...Tilla
...specify that a catch statement should <i>only</i> catch checked exceptions, and that checked exceptions that weren't caught or otherwise flagged to be passed up the call chain would become unchecked exceptions (so a catch surrounding a call to method Foo() could readily distinguish between an InvalidOperationException which was thrown for the reason the Foo() expects, versus one that was thrown by an inner method for reasons Foo() was not expecting.Tilla
V
2

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.

Vaticinate answered 6/1, 2009 at 17:32 Comment(0)
T
1

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.

Throes answered 6/1, 2009 at 17:31 Comment(0)
P
0

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.

Peptone answered 6/1, 2009 at 17:36 Comment(0)
C
0

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.

Christiechristin answered 11/1, 2009 at 15:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.