c# - 如何抛出下溢异常?

标签 c# .net exception

在 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/

相关文章:

exception - Elasticsearch 5.0.0。集群节点未加入

c# - 查找将窗口停靠到左侧/右侧

exception - 如何全局处理 Yesod 中所有处理程序的异常?

wpf - 应用程序级别未处理的异常未创建新文件

C# 外部数据(类似于 iOS Plist)

c# - 确保长时间运行的任务只触发一次,后续请求排队但队列中只有一个条目

c# - 在 C# 中,使用 tick 比较两个日期和按原样比较两个日期有什么区别

c# - gridview 中的 Oracle 数据库表

c# - NETCore.App WebSockets CancellationToken

c# - PowerShell AD 查询与 C# AD 查询 - 速度