tags:

views:

148

answers:

6

I know this sort of code is not best practice, but nevertheless in certain situations I find it is a simpler solution:

if (obj.Foo is Xxxx)
{
   // Do something
}
else if (obj.Foo is Yyyy) 
{
   // Do something
}
else
{
    throw new Exception("Type " + obj.Foo.GetType() + " is not handled.");
}

Anyone know if there is a built-in exception I can throw in this case?

A: 

You could use System.NotSupportedException or just make your own exception based on Exception.

Brian R. Bondy
A: 

Take a look here for a comprehensive list of exceptions. Unfortunately, I don't think any of them fits your problem. It's better to create your own.

Bruno Brant
And I suggest you name it UnsupportedTypeException. :)
Bruno Brant
+3  A: 

If obj is an argument to the method, you should throw an ArgumentException:

throw new ArgumentException("Type " + obj.Foo.GetType() + " is not handled.", "obj");

Otherwise, you should probably either throw an InvalidOperationException or create your own exception, like this:

///<summary>The exception thrown because of ...</summary>
[Serializable]
public class MyException : Exception {
    ///<summary>Creates a MyException with the default message.</summary>
    public MyException () : this("An error occurred") { }

    ///<summary>Creates a MyException with the given message.</summary>
    public MyException (string message) : base(message) { }
    ///<summary>Creates a MyException with the given message and inner exception.</summary>
    public MyException (string message, Exception inner) : base(message, inner) { }
    ///<summary>Deserializes a MyException .</summary>
    protected MyException (SerializationInfo info, StreamingContext context) : base(info, context) { }
}
SLaks
A: 

perhaps System.InvalidOperationException (whatever operation your method is meant to do cannot be done on this data type) ? Or make your own as the others are suggesting

FOR
A: 

If obj is a parameter to your method, I'd throw an ArgumentException. Otherwise, in this case, I'd probably roll my own.

See this Q/A for a rundown on exception guidelines. Basically, there's some built in exceptions that are considered off limits to throw outside the framework. ArgumentException is one of them that is OK.

Aaron Daniels
A: 

Coincidentially, today i found a very nice class from Jared Pars's Weblog, here where he explains a SwitchType class for dealing with this kind of situations.

Usage:

TypeSwitch.Do(
    sender,
    TypeSwitch.Case<Button>(() => textBox1.Text = "Hit a Button"),
    TypeSwitch.Case<CheckBox>(x => textBox1.Text = "Checkbox is " + x.Checked),
    TypeSwitch.Default(() => textBox1.Text = "Not sure what is hovered over"));
Hueso Azul