Python进阶 异常



我们可以使用三种方法来处理多个异常。
第一种方法需要把所有可能发生的异常放到一个元组里。像这样:

try:
    file = open('test.txt', 'rb')
except (IOError, EOFError) as e:
    print("An error occurred. {}".format(e.args[-1]))



对每个单独的异常在单独的except语句块中处理。

try:
    file = open('test.txt', 'rb')
except EOFError as e:
    print("An EOF error occurred.")
    raise e
except IOError as e:
    print("An error occurred.")
    raise e



捕获所有异常:

try:
    file = open('test.txt', 'rb')
except Exception:
    # 打印一些异常日志,如果你想要的话
    raise



包裹到finally从句中的代码不管异常是否触发都将会被执行。这可以被用来在脚本执行之后做清理工作。

try:
    file = open('test.txt', 'rb')
except IOError as e:
    print('An IOError occurred. {}'.format(e.args[-1]))
finally:
    print("This would be printed whether or not an exception occurred!")

# Output: An IOError occurred. No such file or directory
# This would be printed whether or not an exception occurred!



在没有触发异常的时候执行一些代码。这可以很轻松地通过一个else从句来达到。
else从句只会在没有异常的情况下执行,而且它会在finally语句之前执行。

try:
    print('I am sure no exception is going to occur!')
except Exception:
    print('exception')
else:
    # 这里的代码只会在try语句里没有触发异常时运行,
    # 但是这里的异常将 *不会* 被捕获
    print('This would only run if no exception occurs. And an error here '
          'would NOT be caught.')
finally:
    print('This would be printed in every case.')

# Output: I am sure no exception is going to occur!
# This would only run if no exception occurs.
# This would be printed in every case.

你可能感兴趣的:(Python进阶 异常)