例外の処理(try, except, else, finally)

投稿者: | 9月 3, 2022
In [37]: def divide(x, y):
    ...:     try:
    ...:         result = x / y
    ...:     except ZeroDivisionError:
    ...:         print('Divided by Zero!')
    ...:     else:
    ...:         print('Answer is ', result)
    ...:     finally:
    ...:         print('Execute Finally')
    ...: 

In [38]: divide(4, 2)
Answer is  2.0               # tryで例外処理が発生しなかったため、else節が実行された
Execute Finally              # 例外の発生有無にかかわらず、finally節が実行された

In [39]: divide(4, 0)
Diveded by Zero!           # 0で除算したため、例外処理が発生した
Execute Finally              # 例外の発生有無にかかわらず、finally節が実行された

In [40]: divide(4, '2')
Execute Finally              # 例外の発生有無にかかわらず、finally節が実行された
                             # 定義のない例外TypeErrorが発生し、finally節の後に組み込みの例外が実行された

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-40-031ba99acfb4> in <module>
----> 1 divide(4, '2')

<ipython-input-37-cffd366af3c1> in divide(x, y)
      1 def divide(x, y):
      2     try:
----> 3         result = x / y
      4     except ZeroDivisionError:
      5         print('Diveded by Zero!')

TypeError: unsupported operand type(s) for /: 'int' and 'str'

In [41]: 
In [48]: def divide(x, y):
    ...:     try:
    ...:         result = x / y
    ...:     except ZeroDivisionError:
    ...:         print('Divided by Zero!')
    ...:     except:     #最後のexceptの例外名を省略したことで、ワイルードカードとしてクラスExceptionが実行されている。
    ...:         print('please check error type!\n', sys.exc_info())
    ...:     else:
    ...:         print('Answer is ', result)
    ...:     finally:
    ...:         print('Execute Finally')
    ...: 

In [49]: divide(6, 's')
please check error type!
 (<class 'TypeError'>, TypeError("unsupported operand type(s) for /: 'int' and 'str'"), <traceback object at 0x10d875c80>)
Execute Finally