user3310334
user3310334

Reputation:

How to throw an underflow 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.

Upvotes: 3

Views: 5074

Answers (2)

Maksim Simkin
Maksim Simkin

Reputation: 9679

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

Upvotes: 8

galister
galister

Reputation: 430

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

public class UnderflowException : Exception
{

}

Then in your function:

throw new UnderflowException();

Upvotes: 1

Related Questions