正確な例外処理と保証されたクリーンアップ
予測と観察した証拠を記録した後に限り、支援を利用してよい。
Prerequisites
前のアクティビティを完了していること。詰まった場合は記載の回復リンクを使う。
Learning Objective
ファイルのオープンが成功したときと FileNotFoundError を投げたとき、try・except・else・finally のどの節が実行されるかを予測して検証する。手動の close() を with ブロックに置き換え、裸の except が禁止される理由を説明する。
Instructions
try には危険な呼び出しを置く。except FileNotFoundError as e は予期する1種類の失敗だけを処理し、e.filename が見つからないパスを示す。else は例外が起きなかったときだけ実行され、finally は常に実行される。裸の except: は禁止。KeyboardInterrupt や本物のプログラムミスまで飲み込み、診断を当て推量に変えてしまうから。ファイルオブジェクトにとって with は定義済みのクリーンアップ動作であり、finally を不要にする。
Practice & Prediction Log
空の一時フォルダで作業する。このスクリプトを2回実行する:1回目は notes.txt が無い状態で、2回目は printf 'hi\n' > notes.txt で作成した後に。
try:
f = open("notes.txt", encoding="utf-8")
except FileNotFoundError as e:
print("cannot open", e.filename)
else:
print("opened", f.name)
f.close()
finally:
print("cleanup")
各実行の前に、try / except / else / finally のどれが実行されるかと正確な出力を書き出す。その後 (1) else + f.close() の代わりに with ブロックでファイルを閉じるよう書き換え、ブロックの後で f.closed が True であることを示す。(2) 裸の except: が隠してしまうものを2つ挙げる。
実行前に2回分を1行ずつ予測する。次に else/close() 部分を with ブロックに書き換え、finally 節なしでもファイルが閉じることを確認する。
節のトレース。notes.txt が無い場合:open() が FileNotFoundError を投げるので except が実行され、else は飛ばされ、finally が実行される:
cannot open notes.txt
cleanup
notes.txt がある場合:try が成功し、except は飛ばされ、else が実行され(f を閉じ)、finally が実行される:
opened notes.txt
cleanup
with を使った書き換え(with_version.py として保存し、同じ2つの状態で実行する):
def show(path):
try:
with open(path, encoding="utf-8") as f:
print("opened", f.name)
except FileNotFoundError as e:
print("cannot open", e.filename)
return
print("closed after with:", f.closed)
show("notes.txt")
notes.txt がある場合:
opened notes.txt
closed after with: True
notes.txt が無い場合:
cannot open notes.txt
with 文はブロックを抜けるとき(正常終了でも例外でも)必ずファイルを閉じるので、ファイルについては手動の close() も finally 節も不要になる。例外を投げるのは open() 自体なので、except は with の外側に置く。
裸の except: が隠すもの2つ:(1) KeyboardInterrupt(Ctrl+C)と SystemExit。裸の except はすべての BaseException を捕捉するから。(2) タイプミスによる NameError のようなプログラムの誤り。実演:
try:
prnt("hi")
except:
print("something went wrong")
something went wrong
綴りを間違えた print が NameError を投げ、裸の except がそれを曖昧な失敗として報告した。except FileNotFoundError なら、同じタイプミスは問題の行を指す NameError のトレースバックとして表に出る。
成功時と失敗時にどの節が実行されるかを正確に述べ、else/close() パターンを with ブロックに正しく変換し、裸の except が隠すものを2つ挙げられる。
Authoritative Source Resources & Provenance
The Python Tutorial: Errors and Exceptions
該当セクション・タイムスタンプ: Sections 8.3–8.6 (handling exceptions, else, finally, cleanup actions)
検証バージョンと日付: Python 3.12 documentation; verified 2026-10-30
Primary reference for try/except/else/finally semantics and the with statement as predefined cleanup.
Every clause behavior in the lesson is demonstrated by runnable local snippets.
比較対象候補リソースと選定評価 (2)
Solid lecture treatment, but paced for a semester course and requires video viewing; the tutorial section matches the exercise scope directly.
Reference-style exception hierarchy listing rather than the tutorial narrative; retained as lookup material for the recovery drills.