3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Python】独自例外の作成

Posted at

Pythonでの独自例外の作成方法と使い方を簡単にメモしておく。

独自例外の作成

Pythonで独自の例外クラスを定義する場合、Exceptionクラスを親クラスとして継承したクラスを作成する。

sample1
class MyException(Exception):
    pass

また、例外オブジェクトを出力(print())したときに表示されるメッセージを例外クラスで指定することもできる。

sample2
class MyException(Exception):
    def __str__(self):
        return "例外クラス:MyException"

さらに、__init__を使うことで、引数を受け取ることもできる。

独自例外を使う

独自例外もExceptionクラスから派生したクラスであるため、raise <例外名>を使って例外を投げることができる。
例外処理の方法は、他の例外と同じように行うことができる。

# sample1場合
try:
    raise MyException("例外が発生しました!")
except MyException as e:
    print(e)  # 例外が発生しました

# sample2場合
try:
    raise MyException()
except MyException as e:
    print(e)  # 例外クラス:MyException
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?