Code: Alles auswählen
def a():
while True:
try: raise ValueError
finally: break
a()
Stefan
Code: Alles auswählen
def a():
while True:
try: raise ValueError
finally: break
a()
Code: Alles auswählen
>>> while True:
... try:
... raise Exception()
... finally:
... print 'boh'
...
boh
Traceback (most recent call last):
File "<input>", line 3, in <module>
Exception
>>> while True:
... try:
... raise Exception()
... finally:
... break
...
>>>
Vermutlich weil der finally-Block sicherstellen soll, dass der Code in ihm in jedem Fall ausgeführt wird. Das ginge bei return, raise oder break schlecht, wenn die Ausnahme nicht abgefangen würde.sma hat geschrieben:Und warum ist es, wie es ist?
Code: Alles auswählen
def a():
try:
return
finally:
a()
Hey, ausprobieren ist schummeln Wenn man's ausprobiert hat, kann man sich's erklären, finde ich, aber ich hätte das auf den ersten Blick nicht vermutet./me hat geschrieben:Ich habe es mal ausprobiert (Python 2.6).
Irgendwie muss man "break" und "return" innerhalb eines "finally"-Blocks ja sinnvolle Semantik verleihen.If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception, it is re-raised at the end of the finally clause. If the finally clause raises another exception or executes a return or break statement, the saved exception is lost. The exception information is not available to the program during execution of the finally clause.
When a return, break or continue statement is executed in the try suite of a try...finally statement, the finally clause is also executed ‘on the way out.’ A continue statement is illegal in the finally clause. (The reason is a problem with the current implementation — this restriction may be lifted in the future).