Python 将异常传递给下一个Exception语句

Python 将异常传递给下一个Exception语句,python,exception,Python,Exception,我正在尝试捕获异常…Python中的块除外。程序尝试使用os.makedirs创建目录树。如果它引发WindowsError:目录已经存在,我想捕获异常,什么也不做。如果抛出任何其他异常,我将捕获它并设置一个自定义错误变量,然后继续脚本。 理论上可行的方法如下: try: os.makedirs(path) except WindowsError: print "Folder already exists, moving on." except Exception as e: p

我正在尝试捕获异常…Python中的块除外。程序尝试使用os.makedirs创建目录树。如果它引发WindowsError:目录已经存在,我想捕获异常,什么也不做。如果抛出任何其他异常,我将捕获它并设置一个自定义错误变量,然后继续脚本。 理论上可行的方法如下:

try:
    os.makedirs(path)
except WindowsError: print "Folder already exists, moving on."
except Exception as e:
    print e
    error = 1
现在我想对此进行一点增强,并确保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

如何实现我的第一个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
注意,这里我不依赖于异常的容器性质;我要明确地测试
args
属性:

if isinstance(e, WindowsError) and e.args[0] == "directory already exists":

检查异常的类型