2023/10/27 (金) start & done

Python クラスと例外

ここでの話題はクラスに幾らか慣れていないと理解に苦しむかもしれない。
トレースバックで出力されるエラーはPythonのひとつのモジュールで形成されている。そのモジュールを親クラスと考えて、独自の 子クラスでのエラーへの対処となる実装を行うことができる。まずは、classを作成する。

class PracticeFileError(Exception):      ※ Pythonモジュールを取り込んだクラス
    """ モジュール独自の例外の基底クラス"""
class TxtNotFoundError(PracticeFileError):  ※ これが子クラスで継承利用
    def __int__(self):
        self.message = ''

    def alert_message(self, message):
        self.message = message
        print(self.message)

このファイルが独自の例外クラスのモジュールとなる。モジュールとは呼んでも結局はドットpyファイル、つまりPythonファイルなのである。 このモジュールからクラスをインポートして、FileNotFoundErrorへの対処コードを作成する。 このモジュール名をclass_fnf_error.pyとして保存する。

※ class_exception.py名で保存されたファイル
from class_fnf_error import PracticeFileError, TxtNotFoundError

filename = 'THe General Theory of Employment, Interest and Money.txt'    ※ 存在しないファイル

try:
    with open(filename, 'r', encoding='utf-8') as file_object:
        contents = file_object.read()

except FileNotFoundError:
  #インポートしたクラスを利用
    show_error = TxtNotFoundError()
    show_error.alert_message("お探しの.txtファイルが見当たりません。")

else:
    print(contents)

# 実行結果
======== RESTART: C:/Users/******/*****/class_exception.py ========
お探しの.txtファイルが見当たりません。
▲ トップへ戻る


戻る
カテゴリー