How to know when to use an existing Exception or write a custom Exception?
Asked Answered
I

6

4

Thanks for the input on this question, I've decided to go with making my Create() method throw exceptions so as Jon Skeet said, you don't have to handle them everywhere and can just let them bubble up, seems the best approach for larger applications.

So now I create instances of my classes with this code:

try
{
    SmartForms smartForms = SmartForms.Create("ball");
    smartForms.Show();
}
catch (CannotInstantiateException ex)
{
    Console.WriteLine("Item could not be instantiated: {0}", ex.Message);
}

custom exception:

using System;

namespace TestFactory234.Exceptions
{
    class CannotInstantiateException : Exception
    {

    }
}

How do I know which Exception class to use?

In the above instance, I created my own Exception since I don't know where to get a list of "all system exceptions" or if there is one for "not being able to instantiate an object" yet or if it has some other meaning to use it, etc. Choosing an exception type to me has always seems such an arbitrary process, so creating my own seems to be the best idea in general.

Or am I missing something about exceptions? What other implications involved in deciding which Exception type to use?

Include answered 10/6, 2009 at 13:55 Comment(0)
P
5

If the reason you can't create the object is because the argument to Create was invalid, you should probably throw an ArgumentException. However, you could always create our own class derived from ArgumentException if you really want to be able to handle that kind of exception separately to others. (Are you sure you want to?)

Platitudinize answered 10/6, 2009 at 13:58 Comment(3)
But I don't see what using ArgumentException gives me in added value, e.g. when I look at this MSDN example msdn.microsoft.com/en-us/library/system.argumentexception.aspx, you could just as well create an Exception called "MyException" or "JimsException", why "ArgumentException". It's just a name, so it seems arbitrary. What else does ArgumentException give me that e.g. PathTooLongException does not? msdn.microsoft.com/en-us/library/…, they all seem to just return a message, other than that they are just nice names, or what else is there to them?Include
It's more descriptive than anything else - basically it just categorises the exception. It does mean you could catch ArgumentException and get this exception and similar exceptions, but that's unlikely to occur in practice.Platitudinize
I rarely catch ArgumentException actually, unless it is "expected". I regard it like an Assert.Sheol
H
3

Why Create Custom Exceptions? explains in pretty good detail why and when to use the custom exceptions.

Huai answered 10/6, 2009 at 14:0 Comment(4)
This is pretty close to a duplicate.Moxley
Even better, if he gets his answer from the dupe we don't need this Q.Huai
the answers to that question basically say "specific exceptions allow you a finer level of control over your exception handling" which has always been my natural tendency with exceptions, so I don't understand why we need standardized exceptions at all, they seem to me like variable names or method names or class names: it's my application so I can call my Exceptions what I want, so more precisely what advantage do I have in using ArgumentException or using my own ArgumentExceptionWhatever, is there any advantage?Include
Edward, the reason there are built-in exception types is mostly for standardization of the most basic type of exceptions being thrown, and allowing people to not have to reinvent the wheel. I don't think there is any "advantage" to using the standards vs. custom except other than for the fact that you don't HAVE to create your own (laziness as an advantage?)Huai
S
2

Wrote an entire blog post on this subject that you may find interesting

In summary, don't write a custom exception class unless you actually expect someone to both catch and act on the type.

Statfarad answered 10/6, 2009 at 14:2 Comment(0)
Q
1

Create a new type when it might be useful to be able to catch and know a specific exceptional case occured. Is it useful to know that a File wasnt found rather than a generic IO exception ?.

Quevedo answered 10/6, 2009 at 13:57 Comment(1)
If I could type faster, I would have posted nearly the same answer :)Curly
B
1

You will create a custom exception type to provide more contextual information or meaning to the error otherwise you will rely on the runtime generated exception types. For instance an exception like System.DivideByZero exception may not be obvious when it bubbles up to the top in an application. Instead, you could create a custom exception to provide more contextual information in addition to the above 'DivideByZero' error.

For reference on the different runtime generated exceptions, please have a look at MSDN's system namespace. This is not an exhaustive list since exceptions can be generated by native code and also from third party libraries.

Bibliomania answered 10/6, 2009 at 14:14 Comment(0)
S
0

I think a good place to find existing exceptions would be in the help file... if you look up the help for the Exception class, there should be a list of derived classes on the overview page.

How to decide whether to create a new one (derived from Exception), or inherit from an existing one depends on what the exception means.

As Jon says, if your code does some validation on the argument to the Create method, you may want to make an exception derived from ArgumentException (for example maybe an ArgumentNonExistentEntityException if the specified ID does not exist although that is a bit of a mouth full).

If the exception you are creating does not conceptually 'inherit' its meaning from an exception that already exists, just unashamedly create a new one for your library.

Schroder answered 10/6, 2009 at 14:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.