【问题标题】:How to catch an exception and fix the code and then run the function again?如何捕获异常并修复代码然后再次运行该函数?
【发布时间】:2018-11-04 20:07:18
【问题描述】:
global r
global t

def divide(a,b):
    try:
        c=a/b
        print(c)
        return c
    except:
       b+=1000
       r=b
       raise Exception

def main():
    try:
        r=0
        t=1000
        divide(t,r)
    except:
        print('except block')
        divide(t,r)

main()

如何更改变量 r 的值,然后在将其捕获为异常后再次从 except 块中调用该函数?

【问题讨论】:

  • 从它自己的except 块调用函数?使用except ZeroDivisionError:顺便说一句。
  • 对于@Jean-François Fabre 的评论:globals 通常应避免使用。另外,为什么不把所有这些都放在一个类中呢?
  • @AdamMitchell 上课?用于划分 2 个数字?
  • @AdamMitchell OP 不应该使用全局变量这一事实并不能证明在这里使用类是合理的。请参阅 John 对此问题的回答。

标签: python python-3.x exception try-catch try-except


【解决方案1】:

不要在divide 中做任何事情。它的工作不是修复错误的输入参数,也不是捕获由此产生的异常。调用者可以做这些事情。

def divide(a,b):
    c=a/b
    print(c)
    return c

改为在main 中进行更正:

def main():
    try:
        r=0
        t=1000
        divide(t,r)
    except ZeroDivisionError:
        print('except block')
        r+=1000
        divide(t,r)

【讨论】:

  • 这只是一个例子,错误是由变量 r 引起的,因为它是零,但是如果在增加 r 之后可能会发生异常并且需要再次增加,那么必须调用除法函数
  • @ShricharanArumugam 然后你需要一个循环,就像在 any 情况下你想多次做同样的事情。
猜你喜欢
  • 2011-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-27
  • 1970-01-01
  • 2013-11-09
  • 2018-11-18
  • 2014-09-25
相关资源
最近更新 更多