LoginSignup
19
22

More than 5 years have passed since last update.

Pythonの例外処理で例外の内容を知る

Posted at

例外が起きてもプログラムが動くように組みたい。
それでいて
例外が起きたらその内容をちゃんと知りたい。

そんな時に役立つ方法。

sample_square.py
import traceback

while True:
    user_input = input("////////////\nenter number\n////////////\n>>")
    if (user_input == "") or (user_input == ".") or (user_input == "q"):
        break
    try:
        num1 = int(user_input)
    except ValueError:
        print("ValueError. please enter number only")
        continue
    except:
        traceback.print_exc()
        continue
    print("{0}^2={1}".format(num1, num1 ** 2 ))

参考:
http://ja.stackoverflow.com/a/6982/20993

追記

内容を知るだけならもっと簡単に済ませることができるとわかった。

sample.py
try:
    print(1 / 0)
except Exception as e:
    print(e)

Exceptionクラスはすべての例外が当てはまるので、それをeとしておいて表示すれば内容がわかる。

19
22
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
19
22