在 C# 中,我可以抛出溢出异常:
throw new System.OverflowException("Cannot push onto a full stack.");
如何抛出下溢异常?
throw new System.UnderflowException("Cannot pop from an empty stack.");
看起来UnderflowException
不是System
的方法。
最佳答案
没有UnderflowException
。如果您执行以下操作:
var stack = new Stack();
stack.Push(1);
var x1 = stack.Pop();
var x2 = stack.Pop();
你会得到 InvalidOperationException
:
Stack empty.
但是您可以完全自由地创建自己的Exception
类:
public class UnderflowException : Exception
{
public UnderflowException(string message): base(message)
{
}
}
如果你需要,扔掉它:
throw new UnderflowException("Could not pop from empty stack");
关于c# - 如何抛出下溢异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41849215/