pythontry-except

Python try except


try:
    #statement 1
    #statement 2
except Exception, err:
    print err
    pass

This may be very trivial but I never actually thought about it until now and I found myself not being able to answer the following questions:

  1. Does statement 2 gets executed if an error is raised in statement 1?

  2. How does Exception deal with in a case where an error is raised for both statement 1 and statement 2? Which error does it print out in the above code? Both?


Solution

  • The answer is "no" to both of your questions.

    As soon as an error is thrown in a try/except block, the try part is immediately exited:

    >>> try:
    ...     1/0
    ...     print 'hi'
    ... except ZeroDivisionError, e:
    ...     print 'error'
    ...
    error
    >>>
    

    As you can see, the code never gets to the print 'hi' part, even though I made an except for it.

    You can read more here.