Error creation for RPN calculator

I’m confused about how to “fail informatively when there’s not enough values stacked away.” Should I just make a method that prints or returns the string “calculator is empty”, or am I supposed to program in a new type of exception?
If it’s the latter, how is one supposed to do that? I’ve tried to follow some tutorials on creating exceptions, but those weren’t especially helpful beyond letting me know that I need to create a new class. Did I miss a section in the material about creating new exceptions?

Hello Logan,

In 00_rpn_calculator_spec.rb

tells us that if doing a calculation raise an error, which means that the stack is empty or have only 1 value, because doing any calculation requires to pop 2 items from the stack.

If you look at line 50 - 52, it creates an object call @calculator, which should have an instance variable that is a stack (array data structure in this case), and that stack instance variable should be empty at the initialization process when it calls RPNCalculator.new

 before do
    @calculator = RPNCalculator.new
 end

However, it has not use the push method, so the stack now is still empty, and to do any calculation is simple require to pop 2 items form the stack.
All you have to do is to raise an message call “calculator is empty” , should match the exact message. I think there is more than one way to do it. I just simple raise “calculator is empty” if the stack is empty.

Something like this:

if @stack.empty?
    raise "calculator is empty"
end

Good luck, let me know how thing goes for you.

Thanks! The raise "calculator is empty" was just what I needed. I wrote a method to check the length of the stack and raise the error if it was <2. I then called that as part of each of the operator methods before any calculation was done.

2 Likes