What to do if I want to handle different errors, and each error differently in try-except block?
I’m fresh to python so I don’t know
You can have multiple except
. See this example
class B(Exception):
pass
class C(B):
pass
class D(C):
pass
for cls in [B, C, D]:
try:
raise cls()
except D:
print("D")
except C:
print("C")
except B:
print("B")
from the documentation
oh, thank you so much sir/ma’am, I didn’t knew you could have multiple except blocks attached to one try block, thank you so much
They’re matched in order, so keep in mind that you want to provide the
more-specific exceptions first. And you can also test things if just the
exception type is not specific enough. Example:
try:
old_xattr_value_b = os.getxattr(fspath, xattr_name_b)
except OSError as e:
if e.errno not in (errno.ENOTSUP, errno.ENOENT, errno.ENODATA):
raise
old_xattr_value_b = None
Here I want to handle an OSError
for “not supported”, “file not found”
and “no data”. But not other OSError
s (eg “permission denied”). So
I’m looking at the specifics of the OSError
. If it isn’t one of the
ones I expect, I issue a bare raise
statement to reraise the
exception, effectively “uncatching” it.
On the more-specific side of things, these days one can catch “file not
found” and several other specific OSError
types, so the above could
look like:
try:
old_xattr_value_b = os.getxattr(fspath, xattr_name_b)
except FileNotFoundError: # aka OSError ENOENT
old_xattr_value_b = None
except OSError as e:
if e.errno not in (errno.ENOTSUP, errno.ENODATA):
raise
old_xattr_value_b = None
The FileNotFoundError
is a subclass of OSError
. Not all OSError
flavours have a specific named subclass.
Again, note that we’re catching the FileNotFoundError
before the
OSError
.
Also have the ability to accept multiple exception types at once:
except (OSError, ValueError) as ex:
...