0
1

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 5 years have passed since last update.

例外の復習

Last updated at Posted at 2020-01-19
1
l = [1, 2, 3]
i = 5

print('start')
try:
    l[0]
except IndexError as ex:
    print('そのインデックスはありません。{}'.format(ex))
except NameError as ex:
    print('定義されていません。{}'.format(ex))
except Exception as ex:
    print('other: {}'.format(ex))
else:
    print("正常に処理されました。")
finally:
    print("end")
1の実行結果
start
正常に処理されました。
end

どのエラーも発生しないので、
elseブロックとfinallyブロックが実行された。

2
l = [1, 2, 3]
i = 5

print('start')
try:
    l[i]
except IndexError as ex:
    print('そのインデックスはありません。{}'.format(ex))
except NameError as ex:
    print('定義されていません。{}'.format(ex))
except Exception as ex:
    print('other: {}'.format(ex))
else:
    print("正常に処理されました。")
finally:
    print("end")
2の実行結果
start
そのインデックスはありません。list index out of range
end

インデックスが2までしかないのに、
インデックス5を指定し、
IndexErrorが発生する。
なので、
except IndexError as exのブロックとfinallyブロックが実行された。

3
l = [1, 2, 3]
i = 5

del l

print('start')
try:
    l[0]
except IndexError as ex:
    print('そのインデックスはありません。{}'.format(ex))
except NameError as ex:
    print('定義されていません。{}'.format(ex))
except Exception as ex:
    print('other: {}'.format(ex))
else:
    print("正常に処理されました。")
finally:
    print("end")
3の実行結果
start
定義されていません。name 'l' is not defined
end

del lでlがなくなったので、
NameErrorが発生する。
なので、
except NameError as exのブロックとfinallyブロックが実行された。

4
l = [1, 2, 3]
i = 5

print('start')
try:
    l + ()
except IndexError as ex:
    print('そのインデックスはありません。{}'.format(ex))
except NameError as ex:
    print('定義されていません。{}'.format(ex))
except Exception as ex:
    print('other: {}'.format(ex))
else:
    print("正常に処理されました。")
finally:
    print("end")
4の実行結果
start
other: can only concatenate list (not "tuple") to list
end

リストとタプルを足し算するので、
IndexErrorでもNameErrorでもないエラーが発生する。
なので、
except Exception as exのブロックとfinallyブロックが実行された。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?