【问题标题】:(Python) How to stop calculation after a ZeroDivisionError(Python) 如何在 ZeroDivisionError 后停止计算
【发布时间】:2017-02-01 22:31:43
【问题描述】:

有没有办法在异常发生后停止一切?

例如,我正在创建一个反向波兰符号计算器(用于学习后缀),如果我的字符串中有“0”,我想确保打印出“不能被零除”。

我可以使用 try/except 来做我想做的事。

我尝试在异常中的 print 语句之后添加一个“break”,但这显然没有帮助,因为我的最终“pop”在循环之外。这会导致一堆回溯错误,因为显然没有执行“除以零”操作并且列表变得混乱。

有什么想法吗?

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)

【问题讨论】:

  • “停止一切”是什么意思?是否要对调用函数引发异常?你想立即返回一个值吗?你想完全退出 python 吗?
  • 是的,这可能措辞不当。如果出现 0 并发生除法(即发生 ZeroDivisionError),我希望打印出“不能除以零”,仅此而已。目前,我收到了一些除了除以零之外不会发生的错误。也就是说,如果我的列表中没有[0, "/"],则程序完美运行。

标签: python-2.7 stack postfix-notation divide-by-zero try-except


【解决方案1】:

你可以从函数的任何地方返回一个值,而不仅仅是在末尾​​p>

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

当然,无论调用此函数,都必须接受None 作为有效返回值。

或者,如果这是控制链中的一个函数,并且您想一直冒泡到顶部函数,只需重新引发错误,或者引发不同的错误并在最顶级函数。

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')

【讨论】:

  • 效果很好。谢谢!如果我可以问,那究竟是做什么的?根据我的理解,当异常发生时,打印了一些东西,然后“return None”部分结束了程序。如果你能解释一下,那就太棒了。再次感谢!
  • return 只是结束一个函数并向调用函数返回一个值。在函数末尾使用 return 通常是一种很好的做法,但您可以在函数中的任何位置使用 return
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-23
  • 1970-01-01
  • 2017-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多