如何抛出下溢异常?

the*_*sti 3 .net c# exception

在C#中我可以抛出溢出异常:

throw new System.OverflowException("Cannot push onto a full stack.");
Run Code Online (Sandbox Code Playgroud)

如何抛出下溢异常?

throw new System.UnderflowException("Cannot pop from an empty stack.");
Run Code Online (Sandbox Code Playgroud)

它看起来不像UnderflowException是一种方法System.

Mak*_*kin 6

没有UnderflowException.如果你这样做:

var stack = new Stack();
stack.Push(1);
var x1 = stack.Pop();
var x2 = stack.Pop();
Run Code Online (Sandbox Code Playgroud)

你会得到InvalidOperationException:

堆栈空.

但是你可以完全自由地创建自己的Exception类:

public class UnderflowException : Exception
{
    public UnderflowException(string message): base(message)
    {           
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你需要,扔掉它:

throw new UnderflowException("Could not pop from empty stack");
Run Code Online (Sandbox Code Playgroud)