Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw an underflow exception?

Tags:

c#

.net

exception

In C# I can throw an overflow exception:

throw new System.OverflowException("Cannot push onto a full stack.");

How do I throw an underflow exception?

throw new System.UnderflowException("Cannot pop from an empty stack.");

It doesn't look like UnderflowException is a method of System.


2 Answers

There is no UnderflowException. If you do following:

var stack = new Stack();
stack.Push(1);
var x1 = stack.Pop();
var x2 = stack.Pop();

You will get InvalidOperationException :

Stack empty.

But you completely free to create your own Exception class:

public class UnderflowException : Exception
{
    public UnderflowException(string message): base(message)
    {           
    }
}

and throw it if you need:

throw new UnderflowException("Could not pop from empty stack");
like image 168
Maksim Simkin Avatar answered Oct 27 '25 18:10

Maksim Simkin


You can just create your own empty Exception and throw that:

public class UnderflowException : Exception
{

}

Then in your function:

throw new UnderflowException();
like image 29
galister Avatar answered Oct 27 '25 19:10

galister



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!