【问题标题】:Python try/except depending on variablePython try/except 取决于变量
【发布时间】:2016-02-04 20:02:55
【问题描述】:

我需要在程序中继续,除非变量为真但变量为假需要退出程序。 我认为会有 if else 但我不确定如何使用它。

例如:

var = True

try:
    print 2/0
except:
    exit(1)

... continue executing

var = False

try:
    print 2/0
except:
    exit(1)

... exit 

感谢 cmets。

【问题讨论】:

  • 用 if 包裹出口?

标签: python if-statement error-handling try-except


【解决方案1】:

这应该可以解决问题,顺便说一下,您可能应该使用 raise。

var = True

try:
    print 2/0
except:
    if not var:
        # I recommend using raise, as it would show you the error
        exit(1)

【讨论】:

  • 谢谢,什么时候有多个 except 并且我不在每个 except 下都写 'if'?
  • 如果可能的话,用 try/except 包装整个代码块,而不是每一行。查看代码的某些部分确实会有所帮助,因为这种编程风格不是最佳实践。您可以将逻辑封装在一个函数中,然后使用 map() 和参数列表调用它。
  • 是的,它是一个函数,'var' 是 args 之一,见下文
【解决方案2】:

如果您有许多需要使用 var 的 except 组,请尝试此

请注意,您可以使用装饰器或闭包扩展 myexcept,以便在异常中也设置额外的处理。由于函数是一个对象,您可以为您编写的每个except: 使用不同的 specialfunc()。您可以设置 myexcept 以处理带有参数的 specialfunc() 调用,也可以使用如下所示的变量参数过程

def specialfunc1():
     # put the special function code here

def specialfunc2(arg1):
    # put the processing here

def specialfunc3(arg1, arg2):
    # put the processing here

def myexcept(var, e, specialfunc, *args)
    print 'Exception caught for ', e
    if var:
        specialfunc(*args)
    else:
        raise # This raises the current exception to force an exit

try:
    # code you are testing
    2/0
except Error1, e:
    myexcept(var, e, specialfunc1)
except Error2, e:
    myexcept(var, e, specialfunc2(arg1))
except Error3, e:
    myexcept(var, e, specialfunc3(arg1, arg2))
except: # this default forces the regular exception handler

# remaining code

【讨论】:

    猜你喜欢
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 2011-04-25
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多