Nic*_*mer 3 python exception-handling nested try-catch
给定一个未知文件类型的文件,我想用多个处理程序之一打开该文件.如果无法打开文件,则每个处理程序都会引发异常.我想尝试所有这些,如果没有成功,提出异常.
我想出的设计是
filename = 'something.something'
try:
content = open_data_file(filename)
handle_data_content(content)
except IOError:
try:
content = open_sound_file(filename)
handle_sound_content(content)
except IOError:
try:
content = open_image_file(filename)
handle_image_content(content)
except IOError:
...
Run Code Online (Sandbox Code Playgroud)
这种级联似乎不是正确的方法.
有什么建议?
也许您可以对所有处理程序进行分组并在for循环中对它们进行评估,如果没有成功则在最后引发异常.您还可以继续查看引发的异常,从中获取一些信息,如下所示:
filename = 'something.something'
handlers = [(open_data_file, handle_data_context),
(open_sound_file, handle_sound_content),
(open_image_file, handle_image_content)
]
for o, h in handlers:
try:
o(filename)
h(filename)
break
except IOError as e:
pass
else:
# Raise the exception we got within. Also saves sub-class information.
raise e
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
175 次 |
| 最近记录: |