Pass the exception to the next exception

I am getting exceptions with try ... except block in Python. The program tries to create a directory tree using os.makedirs. If it raises WindowsError: The directory already exists, I want to catch the exception and just do nothing. If any other exception is thrown, I'll catch it and set a custom error variable, then continue with the script. In theory, the work would be as follows:

try:
    os.makedirs(path)
except WindowsError: print "Folder already exists, moving on."
except Exception as e:
    print e
    error = 1

      

Now I want to improve this a bit and make sure that the exception block for WindowsError only handles those exceptions where the error message contains "directory already exists" and nothing else. If there is another WindowsError, I want to handle it in the next exception. But unfortunately the following code doesn't work and no exception is thrown:

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

      

How can I make sure that my first exception command catches the "directory already exists" exception on purpose, and all others are handled in the second exception?

+3


source to share


1 answer


Use one block of exceptions and the special case you are working in; you can simply use isinstance()

to catch a specific type of exception:

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

      



Note that I did not rely on the container properties of the exceptions; I would test the attribute args

explicitly:

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

      

+4


source







All Articles