Pythonやってみる!

(105) 独自定義の例外を発生させる。

6,133 views

この記事は最終更新から 2153日 が経過しています。

throw じゃなくて raise と書く。

########################################################################
class MyError(Exception):
    pass

########################################################################
def check_number( n ):
    ret = False
    try:
        if n < 10 :
            raise MyError('%d is too small' % n)
        if n > 100 :
            raise MyError('%d is too big' % n)
        ret = True
    except MyError as e:
        print('<p style="color:#f00">%s</p>' % e.message)
    return ret

実行してみる。

>>> check_number(1)
<p style="color:#f00">1 is too small</p>
False
>>>
>>> check_number(50)
True
>>>
>>> check_number(200)
<p style="color:#f00">200 is too big</p>
False

アクセス数(直近7日): ※試験運用中、BOT除外簡易実装済
  • 2025-09-11: 1回
  • 2025-09-10: 4回
  • 2025-09-09: 3回
  • 2025-09-08: 12回
  • 2025-09-07: 7回
  • 2025-09-06: 6回
  • 2025-09-05: 10回
  • モバイルバージョンを終了