【发布时间】:2014-08-23 17:40:39
【问题描述】:
给定一个未知文件类型的文件,我想使用多个处理程序之一打开该文件。如果无法打开文件,每个处理程序都会引发异常。 我想尝试所有方法,如果没有成功,请引发异常。
我想出的设计是
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:
...
这种级联似乎不是正确的方法。
有什么建议吗?
【问题讨论】:
-
我会推荐 codereview.stackoverflow.com
-
在尝试处理文件之前,有没有办法检查文件的类型?也许是幻数?
-
使用
with会删除一两层try/except -
for opener, handler in [(open_data_file, handle_data_content), ...]:?
标签: python exception-handling nested try-catch