I understand you can do multiple exceptions handling in this way
try:
pass
except EOFError:
deals_with_EOFError()
except FileNotFoundError:
deals_with_FileNotFoundError()
But, I wanted to know how it could be done through something like this
try:
pass
except (EOFError, FileNotFoundError):
if EOFError:
deals_with_EOFError()
else:
deals_with_FileNotFoundError()
You can use built-in type()
to determine the type of the error object.
try:
pass
except (EOFError, FileNotFoundError) as e:
if type(e) is EOFError:
deals_with_EOFError()
else:
deals_with_FileNotFoundError()
However, your initial example has better readability.
try:
pass
except EOFError:
deals_with_EOFError()
except FileNotFoundError:
deals_with_FileNotFoundError()
You can use type()
function of python as follow:
try:
# anything you have to do
except Exception as e:
if type(e) == EOFError:
# do what is necessary
elif type(e) == FileNotFoundError
# do what is necessary
This is because every exception in python is a child of built-in Exception
class of python.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With