非常简单的python 3尝试除了ValueError而不是跳闸

时间:2014-02-27 20:50:49

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

试图让我的尝试除了阻止工作。

import sys

def main():
    try:
        test = int("hello")
    except ValueError:
        print("test")
        raise

main()

输出

C:\Python33>python.exe test.py
test
Traceback (most recent call last):
  File "test.py", line 10, in <module>
    main()
  File "test.py", line 5, in main
    test = int("hello")
ValueError: invalid literal for int() with base 10: 'hello'

C:\Python33>

希望除了旅行

1 个答案:

答案 0 :(得分:5)

您正在重新启动该例外。它按设计工作。

在追溯之前,test打印在顶部,但您使用了raise,因此异常仍然导致追溯:

>>> def main():
...     try:
...         test = int("hello")
...     except ValueError:
...         print("test")
...         raise
... 
>>> main()
test
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in main
ValueError: invalid literal for int() with base 10: 'hello'

删除raise,只删除test打印件:

>>> def main():
...     try:
...         test = int("hello")
...     except ValueError:
...         print("test")
... 
>>> main()
test