os.scandir()
doesn't throw these types of exceptions. It raises the OSError
exception. It does, however, allow you to determine the type of error that occurred.
There are a large number of possible errors that could be part of the OSError
. You can use these to raise your own custom exceptions and then handle them further up the stack.
class OSPermissionError(Exception):
pass
class OSFileNotFoundError(Exception):
pass
try:
os.scandir()
except OSError as error:
# Not found
if error.errno == errno.ENOENT:
raise OSFileNotFoundError()
# Permissions Error
elif error.errno in [errno.EPERM, errno.EACCES]:
raise OSPermissionError()
else:
raise