Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 481
Edward Tanguay Avatar asked Dec 18 '22 07:12

Edward Tanguay


2 Answers

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?)

like image 82
Jon Skeet Avatar answered Dec 19 '22 21:12

Jon Skeet


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

like image 42
TheTXI Avatar answered Dec 19 '22 20:12

TheTXI