0

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!

asked Nov 23, 2016 at 10:25

2 Answers 2

1

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.

answered Nov 23, 2016 at 10:29
Sign up to request clarification or add additional context in comments.

4 Comments

hmmm I was interpreting the question differently, but I see what you are trying to say now.
I will add some further explanation to make it clearer.
If I want to retry when raise the 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?
You are right, in your first method you can do different operations for both kind of exceptions, but the order matters as only one of the exception handlers will be called. If retrying when getting an exception, be sure not to get yourself into an infinite loop.
1

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.

answered Nov 23, 2016 at 10:49

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.