L08 ch01 — try / except / raise
テクノロジ系 / L08 exception — 例外処理
L08 ch01 — try / except / raise
エラーを安全に扱う Python の作法
ゴール
- try / except 構文
- 特定型でキャッチ
- raise で例外を投げる
基本構文
try:
result = 10 / x
except ZeroDivisionError:
result = -1
print(result)複数 except
try:
n = int(input("数値: "))
print(10 / n)
except ValueError:
print("数値ではない")
except ZeroDivisionError:
print("0 で割れない")
except Exception as e:
print(f"その他: {e}")→ 具体的な型から書く (Exception は最後)
raise で投げる
def divide(a: int, b: int) -> int:
if b == 0:
raise ValueError("b must not be 0")
return a // b
try:
divide(10, 0)
except ValueError as e:
print(e) # b must not be 0カスタム例外
class TaskNotFoundError(Exception):
pass
def find_task(id: int):
if id not in tasks:
raise TaskNotFoundError(f"id={id}")→ ドメイン特化のエラー型でキャッチしやすく
try / except / else / finally
try:
f = open("data.txt")
except FileNotFoundError:
print("ファイルなし")
else:
print("成功") # try が成功した時のみ
finally:
f.close() # 必ず実行アンチパターン
# ❌ 裸の except (KeyboardInterrupt まで捕まる)
try:
do_stuff()
except: # ← 型指定なし
pass
# ❌ 例外を握りつぶす
try:
do_stuff()
except Exception:
pass # ← ログも出さないdrill
drill/ — safe_div 関数の実装
力試ししたい方は クイズ形式の演習(任意) もあります。読むだけでも十分です。