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!
2 Answers 2
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.
4 Comments
TimedOutException, the first method is better, but if I just want to print error message when raise every exception, I can use except Exception, doesn't need to add TimedOutException, is right?Multiple except blocks are used if you want to apply different processing:
try:
do_somethong
except TimedOutException as e:
# special processing for timeout
logger.exception(e)
except Exception as e:
# different processing for all other exception
logger.exception(e)
exit(1) # say it is fatal for example...
If you apply same processing group all exceptions in same block, and do not add exception subclasses of classes already present.