Search code examples
pythonpython-3.xpython-os

Try block catches wrong exception


I'm trying to create a folder, handling the different errors (FileExistsError if the folder already exists and OSError if the folder's name contains illegal characters), but Python seems to always choose the first except block when catching an error no matter which one it is and the order they are.

Is there anything I didn't understand?

import os
from pathlib import Path

def generateSetup(name) :
    dir_path = os.path.dirname(os.path.realpath(__file__))
    if not Path(dir_path + '/setups').exists() : os.mkdir(dir_path + '/setups')

    try : os.mkdir(dir_path + '/setups/' + name)
    except FileExistsError : print('The file already exists')
    except OSError : print('The name contains illegal characters')

stp_name = input('Enter your setup\'s name :')
generateSetup(stp_name)

Solution

  • There is nothing wrong with your code. It works properly as intended, catches FileExistsError if the directory already exists or OSError if the directory name contains invalid symbols. So I assume the problem is in the way you are testing the code

    >>> dloc='tmp/\/b'
    >>> try:
    ...     os.mkdir(dloc)
    ... except FileExistsError:
    ...     print('The file already exists')
    ... except OSError:
    ...     print('The name contains illegal characters')
    ... 
    The name contains illegal characters