まあ、もとはといえばtry-except-finallyなど書いていて、データベース接続をどこで閉じるかっていう議論があったわけです。finallyブロックでどうか、なんていうことで議論は収束しました。
しかしながらここで「え」「これfinallyこないんじゃない」「無理だよ」「unreachable」っていう指摘が出てきたわけなんです。tryブロックで値を返していたわけなんですね。finallyへは来ないんじゃ…
しばらくして「あれ?」って声が上がりました。これです。
この結果は…(走らせてみてください)。
tryブロックで終了するコードだと起きる現象ですね。
実はこれ、Javaでも同様です(走らせてみてください)。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def foo(): | |
try: | |
return 'try' | |
except: | |
return 'except' | |
finally: | |
return 'finally' | |
print(foo()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def foo(): | |
for i in range(5): | |
try: | |
break; | |
except: | |
return 'except' | |
finally: | |
print( 'finally') | |
print(foo()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TryTest{ | |
static String foo(){ | |
try{ | |
return "try"; | |
}catch(Exception e){ | |
System.out.println("except"); | |
}finally{ | |
return "finally"; | |
} | |
} | |
public static void main(String args[]){ | |
System.out.println(TryTest.foo()); | |
} | |
} |