3

I want to handle specific OSError codes like this:

try:
    os.scandir()
except OSPermissionError as error:  
    # Only catch errno.EACCES, errno.EPERM
    handle_permission_error()
except OSFileNotFoundError as error: 
    # Only catch errno.ENOENT
    handle_FileNotFoundError_error()

Can this be done in python?

Buoy
  • 795
  • 1
  • 8
  • 13

2 Answers2

7

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
Community
  • 1
  • 1
Andy
  • 49,085
  • 60
  • 166
  • 233
  • Thanks!, So it does not work to put the errno test in the subclass beforehand, sigh. – Buoy Feb 03 '16 at 16:57
3

You can do this:

try:
    os.scandir()
except OSError as error:
    if error.errno in (errno.EACCES, errno.EPERM): #Permission denied
        handle_permission_error()
    elif error.errno == errno.ENOENT: #File not found
        handle_FileNotFoundError_error()
    else:
        raise
zondo
  • 19,901
  • 8
  • 44
  • 83
  • Thanks! This is exactly the way my code is written. I was hoping I was missing some feature of Exception but from these answers it appears there is no such ability to include the errno test in the subclass. – Buoy Feb 03 '16 at 14:52