【问题标题】:How to make exception syntax from 2.** to 3.** work如何使异常语法从 2.** 到 3.** 工作
【发布时间】:2016-06-24 08:13:09
【问题描述】:
def no():
    try:
        x = eval(input('Enter a number: '))
        y = eval(input("Enter a number: "))
        print(x/y)
    except (ZeroDivisionError, TypeError) , e:
        print('The second number cannot be zero!', e)

如何在 3.** python 中完成这项工作

【问题讨论】:

  • 您应该始终使用as e 而不是, e。它适用于 Python2 和 Python3,因此使用 as 使其双向兼容。
  • @zondo:这在 Python 2.5 或更早版本中不起作用。

标签: python exception try-catch except


【解决方案1】:

Python 2.6 及更高版本支持新的except .. as 语法,只需使用它:

def no():
    try:
        x = eval(input('Enter a number: '))
        y = eval(input("Enter a number: "))
        print(x/y)
    except (ZeroDivisionError, TypeError) as e:
        print('The second number cannot be zero!', e)

请参阅Python 2.6 What's new document

除非您需要支持 2.5 或更早版本,否则无需在任何代码中使用旧的、已弃用的 except .., e: 语法,此时您唯一的选择是在处理程序中使用 sys.exc_info() 来访问当前活动的异常:

def no():
    try:
        x = eval(input('Enter a number: '))
        y = eval(input("Enter a number: "))
        print(x/y)
    except (ZeroDivisionError, TypeError):
        # avoid using "as e" to support Python <= 2.5.
        e = sys.exc_info()[1]
        print('The second number cannot be zero!', e)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 2012-04-29
    相关资源
    最近更新 更多