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
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!")
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With