我在Python中使用try ... except块捕获异常。该程序尝试使用os.makedirs创建目录树。如果引发WindowsError:目录已存在,我想捕获异常,什么也不做。如果引发任何其他异常,我将捕获该异常并设置一个自定义错误变量,然后继续执行脚本。理论上的工作如下:
try:
os.makedirs(path)
except WindowsError: print "Folder already exists, moving on."
except Exception as e:
print e
error = 1
Run Code Online (Sandbox Code Playgroud)
现在,我想对此加以增强,并确保WindowsError的except块仅处理那些错误消息包含“目录已存在”且没有其他内容的异常。如果还有其他WindowsError,我想在下一个except语句中处理它。但不幸的是,以下代码不起作用,并且没有捕获到异常:
try:
os.makedirs(path)
except WindowsError as e:
if "directory already exists" in e:
print "Folder already exists, moving on."
else: raise
except Exception as e:
print e
error = 1
Run Code Online (Sandbox Code Playgroud)
如何实现我的第一个except语句专门捕获“目录已存在”异常,而所有其他语句在第二个except语句中得到处理?
使用一个异常块,并在特殊情况下在那里进行处理;您只可以isinstance()
用来检测特定的异常类型:
try:
os.makedirs(path)
except Exception as e:
if isinstance(e, WindowsError) and "directory already exists" in e:
print "Folder already exists, moving on."
else:
print e
error = 1
Run Code Online (Sandbox Code Playgroud)
注意,这里我不依赖于异常的类似容器的性质。我会args
明确测试属性:
if isinstance(e, WindowsError) and e.args[0] == "directory already exists":
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
818 次 |
最近记录: |