There are a number of built-in exceptions in Python that can be thrown by various standard library functions (and, of course, other code). Some exceptions could potentially be triggered for many reasons, and you can find out if they were thrown for a specific reason.
For example, on Windows, if you try to move a file when it is locked by another process, you will most likely get PermissionError:
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Path\\to\\the\\file'
In my case, I want to determine if the cause of exception a occurs PermissionErrorbecause the file I'm trying to move is locked, and I'm currently doing this by looking at the error message in the exception that I catch
try:
# Move file
os.rename(source_path, dest_path)
except PermissionError as e:
if str(e).find('The process cannot access the file because it is being used by another process') != -1:
# File not unlocked yet; do something, e.g. wait a moment and try again
else:
# Exception thrown for some other reason; do something else
, , str(e) , , , , os.rename, , . , Python Python.
, , PermissionError - , , , PermissionError? , , , ?