LoginSignup
0
0

More than 3 years have passed since last update.

【Udemy Python3入門+応用】  66. 独自例外の作成

Posted at

※この記事はUdemyの
現役シリコンバレーエンジニアが教えるPython3入門+応用+アメリカのシリコンバレー流コードスタイル
の講座を受講した上での、自分用の授業ノートです。
講師の酒井潤さんから許可をいただいた上で公開しています。

■独自例外の作成

◆raise

raise IndexError('test error')
result
Traceback (most recent call last):
  File "/~~~", line 1, in <module>
    raise IndexError('test error')
IndexError: test error

raise を使うことで、指定したエラーを引き起こすことができる。

◆独自のエラーを作る

class UppercaseError(Exception):
    pass

def check():
    words = ['APPLE', 'orange', 'banana']
    for word in words:
        if word.isupper():
            raise UppercaseError(word)

check()
result
Traceback (most recent call last):
  File "/~~~", line 10, in <module>
    check()
  File "/~~~", line 8, in check
    raise UppercaseError(word)
__main__.UppercaseError: APPLE

このように、プログラム内で自分で作ったエラーを発生させることができるようになる。

class UppercaseError(Exception):
    pass

def check():
    words = ['APPLE', 'orange', 'banana']
    for word in words:
        if word.isupper():
            raise UppercaseError(word)

try:
    check()
except:
    print('This is my fault. Go next.')
result
This is my fault. Go next.

このようにしておくと、処理内でエラーが発生したときに、
「これはPythonのデフォルトのエラーではなくて、自分で作ったエラーが発生しているんだな」
と認識できるようになるため、開発で便利。

0
0
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
0
0