try – except – else – finally ブロック
Python
try:
file = open("sample.txt", "r")
content = file.read()
except FileNotFoundError as e:
print(f"エラーが発生しました: {e}")
else:
print("エラーなしでファイル読み込み完了")
finally:
print("処理完了(後処理実行)")
カスタム例外と raise
Python
class AgeValueError(Exception):
"""年齢指定エラー用の自作例外クラス"""
pass
def check_age(age):
if age < 0:
raise AgeValueError("年齢は0以上で指定してください")
try:
check_age(-5)
except AgeValueError as e:
print(e)
with 構文による安全なファイル読み書き
with 構文(コンテキストマネージャ)を使用すると、ファイルの閉じ忘れ(クローズ漏れ)を防止できます。
Python
import json
# テキスト書き込み
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Python学習")
# JSON読み込み
with open("config.json", "r", encoding="utf-8") as f:
config = json.load(f)

コメント