0
1

More than 3 years have passed since last update.

raise で 意図的に例外を投げかける

Posted at
import sys, traceback

number1 = 100
number2 = 1

print('start')
try:
    print(1)
    raise NameError('意図的にネームエラーを発生させました。')
    print(2)
except NameError as e:
    print('未定義の変数を呼び出しました。')
    sys.stderr.write(traceback.format_exc())
finally:
    print('end')
実行結果
start
1
未定義の変数を呼び出しました。
end

tryブロックのraise NameError より後ろにある
print(2)は実行されないことに注意。

実行時エラー
Traceback (most recent call last):
  File "Main.py", line 9, in <module>
    raise NameError('意図的にネームエラーを発生させました。')
NameError: 意図的にネームエラーを発生させました。
0
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
0
1