代码之家  ›  专栏  ›  技术社区  ›  cbp

C:当需要某个类型时引发异常

  •  2
  • cbp  · 技术社区  · 15 年前

    我知道这类代码不是最佳实践,但在某些情况下,我发现它是一个更简单的解决方案:

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

    有人知道我是否可以在这个案例中抛出一个内置的异常吗?

    6 回复  |  直到 15 年前
        1
  •  3
  •   SLaks    15 年前

    如果 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) { }
    }
    
        2
  •  0
  •   Brian R. Bondy    15 年前

    你可以使用 System.NotSupportedException 或者只是根据例外情况做出自己的例外。

        3
  •  0
  •   Bruno Brant    15 年前

    看一看 here 获取一个完整的例外列表。不幸的是,我认为这些都不适合你的问题。最好是自己创造。

        4
  •  0
  •   FOR    15 年前

    可能是System.InvalidOperationException(方法要执行的任何操作都不能在此数据类型上执行)?或者按照别人的建议做你自己的

        5
  •  0
  •   Community CDub    8 年前

    如果obj是您方法的参数,我将抛出 ArgumentException .否则,在这种情况下,我可能会自己滚。

    this Q/A 关于异常准则的概要。基本上,有一些内置的异常被认为是超出框架的限制。 参数异常 是其中一个没问题的。

        6
  •  0
  •   Hueso Azul    15 年前

    巧合的是,今天我在Jared 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"));