Python try except

后端 未结 5 1532
[愿得一人]
[愿得一人] 2021-01-19 00:12
try:
    #statement 1
    #statement 2
except Exception, err:
    print err
    pass

This may be very trivial but I never actually thought about it

相关标签:
5条回答
  • 2021-01-19 00:56

    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.

    0 讨论(0)
  • 2021-01-19 00:56

    Upon an exception being raised control leaves the try block at the point the exception is raised and is given to the appropriate except block. If statement 1 throws an exception, statement 2 will not execute.

    This answers your second question as well: it's not possible for the scenario you describe to happen.

    0 讨论(0)
  • 2021-01-19 01:00

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

    nope, statement 2 is not executed

    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?

    only statement 1 has a chance to raise an error, see above,

    NOTE: if you want statement 2 to execute always, you can use finally with the try/except

    0 讨论(0)
  • 2021-01-19 01:03

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

    No. Exception will be raised and catched. As I understand python will move up the stack and looks for an exception handler in the caller

    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?

    statement 2 will not be run so no exceptions will be raised for it

    any exception from the try block will be caught. That is why for all try/except clauses, limit the try clause to the absolute minimum amount of code necessary. Again, this avoids masking bugs.

    0 讨论(0)
  • 2021-01-19 01:06

    From Python docs:

    If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.

    So as soon as an error occurs, it skips to the exception

    http://docs.python.org/2/tutorial/errors.html

    0 讨论(0)
提交回复
热议问题