LoginSignup
5
5

More than 3 years have passed since last update.

Python、例外処理について

Last updated at Posted at 2020-03-23

例外処理についてメモ

例外処理とは途中でエラーが発生してプログラムが中断しないようにする処理
例えば以下を実行してみる。

list = [1,2,3,4,'a',5,6]
for i in list:
   print(i/10)

とすると、

0.1
0.2
0.3
0.4
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-21-78c5fd70e082> in <module>
      2 
      3 for i in list:
----> 4     print(i/10)

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

"a"表記のためエラーが発生し、プログラムが中断してしまう。
そこで、エラー表記をする。

for i in list:
    try:
        print(i/10)
    except:
        print("Error")
0.1
0.2
0.3
0.4
Error
0.5
0.6

うまくいった。

5
5
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
5
5