print("Found config.txt but it is a directory, couldn't read it")
复制代码
现在在 config.txt 目次地点的位置再次运行它:
python3 config.py
Found config.txt but couldn't read it
现在删除 config.txt 目次,以确保改为访问第一个 except 块:
rm -f config.txt
python3 config.py
Couldn't find the config.txt file!
如果错误具有类似的性质,并且无需单独处理,则可以通过在 except 行中使用括号将异常归为一组。 比方,如果导航系统负载过大,并且文件系统变得太忙,则很有必要同时捕捉 BlockingIOError 和 TimeOutError:
def main():
try:
configuration = open('config.txt')
except FileNotFoundError:
print("Couldn't find the config.txt file!")
except IsADirectoryError:
print("Found config.txt but it is a directory, couldn't read it") except (BlockingIOError, TimeoutError): print("Filesystem under heavy load, can't complete reading configuration file")
复制代码
即使可以将异常归为一组,也只有在不必要单独处理异常时才如许做。 制止将多个异常归为一组以提供普通的错误消息。
如果必要访问与异常相关的错误,则必须更新 except 行以包含 as 关键字。 如果异常太过普通,则这种方法就非常方便并且错误消息会很有效:
try:
open("mars.jpg")
except FileNotFoundError as err:
print("Got a problem trying to read the file:", err)