Skip to main content
 首页 » 编程设计

python之异常被延迟抛出

2025年05月04日15JeffreyZhao

我在 Python 中有以下脚本:

import sys 
 
 
for filename in sys.argv: 
    with open(filename, mode='r') as f: 
        print("Foobar") 

如果我使用一个不存在的文件名作为参数启动脚本,我会如预期的那样得到一个异常。但是,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' 

这是为什么?

请您参考如下方法:

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

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