pangpang pangpang - 11 days ago 7
Python Question

python handle multi exceptions

I wrote the code as below:

try:
do_somethong
except TimedOutException as e:
logger.exception(e)
except Exception as e:
logger.exception(e)


is this same with below code?

try:
do_somethong
except (TimedOutException, Exception) as e:
logger.exception(e)


I know
TimedOutException
is subclass of
Exception
, should I remove
TimedOutException
? Anyone can explain it for me? Thanks in advance!

Answer

WARNING: except Exception as e: should not be used as it groups every exception that inhetirts from it (most of the exceptions inherit from Exception except for a couple python related ones)

If still wanting to use Exception, TimedOutException would not be necesary.

When handling exceptions, every exception that is an instance of the class used in the except clause, or any child class from it, gets handled, so having Exception basically handles 99% of exceptions. That is the reason why Exception is not recommended as a class for this purpouse unless you are just logging and raising the same exception again with raise.

When using multiple except clauses, the order is important, as any exception will only get handled by the first except clause that matches the type.

Comments