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?
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?)
Why Create Custom Exceptions? explains in pretty good detail why and when to use the custom exceptions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With