0
0

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.

例外処理 その1 -初心者メモ

Posted at

例外処理とは、エラーが出る可能性がある処理に対して、エラーが出ても(例外が発生しても)、代わりに実行される処理のこと。

def div(num1,num2):
  try:
    print(f'Answer= {num1/num2}')
 
 except ZeroDivisionError as e:
    print(e)

  except TypeError as t:
    print(t)

  else:
    print('正常に終了')

  finally:
    print('すべての処理が終了')

tryしてみて、エラーならexcept以下が実行される。

elseは、tryが成功したときに表示される。

finallyはtryの成功失敗にかかわらず実行される。

出力結果例

div(1,2)
#Answer= 0.5
#正常に終了
#すべての処理が終了

divide(1,0)
#division by zero
#すべての処理が終了しました
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?