2

Is there a way to stop everything after an exception?

For example, I'm creating a reverse polish notation calculator (to learn postfix) and I want to make sure "Cannot divide by zero" is printed out if there is a "0" in my string.

I got it to do what I wanted using try/except.

I tried putting in a "break" after my print statement in the exception but that obviously does not help because my final "pop" is outside the loop. And that causes a bunch of traceback error as obviously the "divide by zero" operation was not performed and the list becomes messed up.

Any ideas?

def RPN(ll):
    mys = Stack()
    for x in ll:
        if x == '+':
            sum_of_two = mys.new_pop() + mys.new_pop()
            mys.push(sum_of_two)
            """mys.print_stack()"""           #test addition

        elif x == "*":
            product = mys.new_pop() * mys.new_pop()
            mys.push(product)
            """mys.print_stack()"""             #test multiplication

        elif x == "-":
            subtrahend = mys.new_pop()
            minuend = mys.new_pop()
            subtrahend
            minuend
            difference = minuend - subtrahend
            mys.push(difference)
            """mys.print_stack()"""             #test subtraction

         elif x == "/":
            divisor = mys.new_pop()  
            dividend = mys.new_pop()
            divisor
            dividend
            try: 
                quotient = dividend/divisor
                mys.push (quotient)
            except ZeroDivisionError:
                print "Cannot divide by zero"
            """mys.print_stack()"""                #test division

         else:
            mys.push(int(x))

    return mys.new_pop()


example = [3,4,"-",5,"+",6,"*",0,"/"]        #test reverse polish calc
print RPN(example)
DudeWah
  • 359
  • 3
  • 20
  • What do you mean by "stop everything"? Do you want to raise an exception to the calling function? Do you want to return a value immediately? Do you want to quit python entirely? – Brendan Abel Sep 24 '16 at 00:42
  • Yes that might have been worded poorly. If a 0 comes up and division occurs (i.e. a ZeroDivisionError happens) I would like for "Cannot divide by zero" to be printed out and that's it. Currently I am receiving a few errors that do not happen except in the case of division by zero. That is to say, if there is no [0, "/"] in my list, the program runs perfectly. – DudeWah Sep 24 '16 at 00:46

1 Answers1

0

You can return a value from anywhere in a function, not just at the end

try: 
    quotient = dividend/divisor
    mys.push(quotient)
except ZeroDivisionError:
    print 'Something to console'
    return None

Of course, whatever called this function is going to have to accept None as a valid return value.

Alternatively, if this is a function way down in the control chain, and you want to just bubble all the way up to the top function, just re-raise the error, or raise a different error and catch it at the very top function.

class MyError(Exception):
    pass

def func():
    try:
        func2()
    except MyError as e:
        print e.message

def func2():
    func3():

def func3():
    RPN([...])

def RPN(ll):
    ...
    try:
        ...
    except ZeroDivisionError:
        raise MyError('Zero Division')
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118
  • That worked very nicely. Thank you! If I may ask, what exactly did that do? From my understanding when the exception occurred, something was printed and then the "return None" part ended the program. If you could explain a little bit that would be awesome. Thanks again! – DudeWah Sep 24 '16 at 00:51
  • `return` just ends a function and returns a value to the calling function. It's generally good practice to `return` at the end of a function, but you can `return` from anywhere in the function. – Brendan Abel Sep 24 '16 at 00:55