异常被推迟了

pet*_*ohn 1 python exception

我在Python中有以下脚本:

import sys


for filename in sys.argv:
    with open(filename, mode='r') as f:
        print("Foobar")
Run Code Online (Sandbox Code Playgroud)

如果我使用不存在的文件名作为参数启动脚本,我会得到一个异常,如预期的那样.但是,print()即使我不希望它仍在执行中.

Foobar
Traceback (most recent call last):
  File "home/bin/ksp-increment-build", line 16, in <module>
    with open(filename, mode='r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'asdads'
Run Code Online (Sandbox Code Playgroud)

为什么是这样?

Mar*_*ste 6

第一个元素sys.argv是脚本自身运行的路径,因此可以正确打开.

第二个元素是不存在的文件名,它在打印函数之前抛出错误.