gpt4 book ai didi

C#:预期某种类型时抛出的异常

转载 作者:行者123 更新时间:2023-11-30 22:46:36 25 4
gpt4 key购买 nike

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

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

有人知道在这种情况下是否可以抛出内置异常吗?

最佳答案

如果 obj 是方法的参数,你应该抛出 ArgumentException :

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

否则,您可能应该抛出 InvalidOperationException或创建您自己的异常(exception),如下所示:

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

关于C#:预期某种类型时抛出的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2557659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com