Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: try/except/else and continue statement

Why is the output of the below python code snippet NOT just No exception:1, since during first iteration there is no exception raised. From python docs (https://docs.python.org/2.7/tutorial/errors.html).

The try ... except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception.

$ cat hello.py
for x in range(1,10):
  try:
    if x == 1:
        continue
    x/0
  except Exception:
    print "Kaput:%s" %(x)
  else:
    print "No exception:%s" %(x)
    break

$ python hello.py
  Kaput:2
  Kaput:3
  Kaput:4
  Kaput:5
  Kaput:6
  Kaput:7
  Kaput:8
  Kaput:9

 $ python -V
 Python 2.7.8
like image 884
sateesh Avatar asked May 06 '17 03:05

sateesh


People also ask

How do you do continue in try and except in Python?

Continue in Error Handling—Try, Except, Continue. If you need to handle exceptions in a loop, use the continue statement to skip the “rest of the loop”. print("... But I don't care!") for number in [1, 2, 3]: try: print(x) except: print("Exception was thrown...") print("... But I don't care!")

Does code continue after Except Python?

The try and except block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program's response to any exceptions in the preceding try clause.

Is it a good practice to use try-except else in Python?

The except block should only catch exceptions you are prepared to handle. If you handle an unexpected error, your code may do the wrong thing and hide bugs. An else clause will execute if there were no errors, and by not executing that code in the try block, you avoid catching an unexpected error.

Can we use else with try and except?

The 'else' block of a try-except clause exists for code that runs when (and only when) the tried operation succeeds. It can be used, and it can be abused.


1 Answers

The tutorial gives a good start, but is not the language reference. Read the reference here.

Note in particular:

The optional else clause is executed if and when control flows off the end of the try clause.

clarified by footnote 2:

Currently, control “flows off the end” except in the case of an exception or the execution of a return, continue, or break statement.

So your use of continue is explicitly addressed by that.

like image 90
Tim Peters Avatar answered Oct 24 '22 15:10

Tim Peters