try:
print("TRY")
finally:
print("FINALLY")
# 出力:TRY
# 出力:FINALLY
try:
print("TRY")
1 / 0
finally:
print("FINALLY")
# 出力:TRY
# 出力:FINALLY
# 出力:Traceback (most recent call last):
# 出力: File "~.py", line ~, in <module>
# 出力: 1 / 0
# 出力:ZeroDivisionError: division by zero
import sys
try:
print("TRY")
1 / 0
except:
print("EXCEPT")
print("SYS.EXC_INFO:", sys.exc_info())
finally:
print("FINALLY")
# 出力:TRY
# 出力:EXCEPT
# 出力:SYS.EXC_INFO: (<class 'ZeroDivisionError'>, ZeroDivisionError('division by zero'), <traceback object at 0x~>)
# 出力:FINALLY
try:
print("TRY")
print("例外なし")
except:
print("EXCEPT")
else:
print("ELSE")
finally:
print("FINALLY")
# 出力:TRY
# 出力:例外なし
# 出力:ELSE
# 出力:FINALLY
try:
print("TRY")
print("例外あり")
1 / 0
except:
print("EXCEPT")
else:
print("ELSE")
finally:
print("FINALLY")
# 出力:TRY
# 出力:例外あり
# 出力:EXCEPT
# 出力:FINALLY
for i in range(10):
try:
print("TRY")
print("例外なし", i)
if i == 2:
break
except:
print("EXCEPT")
else:
print("ELSE")
finally:
print("FINALLY\n")
# 出力:TRY
# 出力:例外なし 0
# 出力:ELSE
# 出力:FINALLY
# 出力:TRY
# 出力:例外なし 1
# 出力:ELSE
# 出力:FINALLY
# 出力:TRY
# 出力:例外なし 2 【elseの処理なし】
# 出力:FINALLY
class UserError(EOFError, IndexError, SyntaxError):
pass
lst = [
None,
EOFError,
ImportError,
IndexError,
SyntaxError,
UserError,
]
for err in lst:
try:
print("TRY", err)
if err != None:
raise err
except EOFError as e:
print("EXCEPT (1)", type(e))
except (ImportError, IndexError) as e:
print("EXCEPT (2)", type(e))
except:
print("EXCEPT (ETC)")
else:
print("ELSE")
finally:
print("FINALLY\n")
# 出力:TRY None
# 出力:ELSE
# 出力:FINALLY
# 出力:TRY <class 'EOFError'>
# 出力:EXCEPT (1) <class 'EOFError'>
# 出力:FINALLY
# 出力:TRY <class 'ImportError'>
# 出力:EXCEPT (2) <class 'ImportError'>
# 出力:FINALLY
# 出力:TRY <class 'IndexError'>
# 出力:EXCEPT (2) <class 'IndexError'>
# 出力:FINALLY
# 出力:TRY <class 'SyntaxError'>
# 出力:EXCEPT (ETC)
# 出力:FINALLY
# 出力:TRY <class '__main__.UserError'>
# 出力:EXCEPT (1) <class '__main__.UserError'>
# 出力:FINALLY