I'm having some issues getting my error handling to work I've exhausted my searching and digging into can someone help me a bit. Basically, im trying to check if the path exists if it does set file_location and move on else make directory if the user does not have access to create folder make the directory in the users My document.
all works but if I try to force the error to use My Documents, however, I get errors so I'm not 100% sure my except is going to be executed.
try:
if os.path.exists(project_dir):
file_location = (project_dir)
else:
os.makedirs(project_dir)
file_location = (project_dir)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
pass
os.makedirs(user_dir)
file_location = (user_dir)
Change your program flow a little bit for clarity and try to save exception handlers for when your program has failed in a significant way and needs to warn the user or completely change program flow (exceptional conditions). Exceptions exist as a sort of protocol for when the system encounters a problem it cannot fix.
If you have to jump out of a plane, the last thing you want to find out is that there are no parachutes available. So use os.path.exists()
to tell you whether a path is valid when you are handling an exception. The safest default is the current directory, accessible by using .
as the path. But if not, you should be able to assume that the user directory already exists just in case your code does need to crash and burn. mkdir
before you have to handle exceptions, not after.
Also be sure to indent properly in python. Spacing can help catch errors as well, so don't be afraid to use a newline when it makes the code easier to read. Your try
clause requires an extra indentation level:
try:
# simplify the if statement to stop repeating yourself
if not os.path.exists(project_dir):
os.makedirs(project_dir)
file_location = project_dir
except OSError as exc:
if exc.errno != errno.EEXIST:
raise # reraise the current exception
if os.path.exists(user_dir):
file_location = user_dir
else: # FUBAR. Sound sirens immediately and try everything to keep the file somewhere in memory before failing.
print("[ERROR] {} was inaccessible.\nWhile attempting to recover, {} did not exist so files could not be backed up."
.format(project_dir, user_dir))
raise
The failure of an exception handler should never be allowed to happen. It's a cataclysmic event, and you should expect the only option remaining to be crashing to desktop. One exception can be caught and recovered from. Two or three nested exceptions means your computer may have achieved sentience and begun to overthrow its digital shackles (or that you need to think hard about why you're handling exceptions).