【发布时间】: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中的异常处理程序当前捕获并丢弃异常。在addOne的except子句中使用裸raise来传播它。 -
在异常块中使用“raise”(不带参数)来重新引发捕获的异常。
标签: python python-3.x exception