【问题标题】:How can my program know an exception from a separate method [duplicate]我的程序如何从单独的方法中知道异常[重复]
【发布时间】:2020-03-03 13:33:26
【问题描述】:

我正在编写一个 python 程序。 它调用具有 try...except... 的私有方法并返回一个值。 如:

def addOne(x):
    try:
        a = int(x) + 1
        return a
    except Exception as e:
        print(e)
def main():
    x = input("Please enter a number: ")
    try:
        y = addOne(x)
    except:
        print("Error when add one!")

main()

当我输入一个无效的输入“f”时,输出是这样的

Please enter a number: f
invalid literal for int() with base 10: 'f'

我想检测 main() 和 addOne(x) 中的异常 所以理想的输出可能如下所示:

Please enter a number: f
invalid literal for int() with base 10: 'f'
Error when add one!

谁能告诉我怎么做?谢谢!

【问题讨论】:

  • addOne 中的异常处理程序当前捕获并丢弃异常。在addOneexcept 子句中使用裸raise 来传播它。
  • 在异常块中使用“raise”(不带参数)来重新引发捕获的异常。

标签: python python-3.x exception


【解决方案1】:

处理异常可防止其进一步传播。要允许在外部范围内处理异常,请在异常处理程序中使用裸 raise

def addOne(x):
    try:
        a = int(x) + 1
        return a
    except Exception as e:
        print(e)
        raise  # re-raise the current exception

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多