2010-04-01 10 views
2

我知道這種代碼是不是最好的做法異常拋出,但儘管如此,在某些情況下,我發現這是一個簡單的解決方案:C#:當某一類型的預計

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."); 
} 

任何人都知道,如果有我可以在這種情況下拋出一個內置的異常?

回答

3

如果obj是一個參數的方法,你應該拋出一個ArgumentException

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

否則,你應該要麼拋出一個InvalidOperationException,或者創建自己的異常,如:

///<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) { } 
} 
0

您可以使用System.NotSupportedException或根據異常製作您自己的異常。

0

查看here以查看完整的例外情況列表。不幸的是,我不認爲它們中的任何一個都適合你的問題。最好創建自己的。

+0

我建議你的名字UnsupportedTypeException。 :) – 2010-04-01 01:49:35

0

也許是System.InvalidOperationException(無論你的方法意味着做什麼操作都無法在此數據類型上完成)?或者讓別人建議你自己

0

如果obj是你的方法的參數,我會拋出一個ArgumentException。否則,在這種情況下,我可能會推出自己的產品。

查看this Q/A瞭解異常指導原則。基本上,有一些內置的例外被認爲是超出框架限制的。 ArgumentException就是其中之一。

0

重合,今天我從Jare​​d Pars的博客here中找到了一個很好的類,他在那裏解釋了一個用於處理這種情況的SwitchType類。

用法:

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"));