3

Python 1.5.2で例外のタイプを取得するにはどうすればよいですか?

これを行う:

try:
    raise "ABC"
except Exception as e:
    print str(e)

SyntaxErrorを与えます:

  except Exception as e:
                    ^

SyntaxError: invalid syntax

編集: これは機能しません:

try:
    a = 3
    b = not_existent_variable
except Exception, e:
    print "The error is: " + str(e) + "\n"

a = 3
b = not_existent_variable

実際のエラー(NameError)ではなく、引数のみを取得するため、次のようになります。

The error is: not_existent_variable

Traceback (innermost last):
  File "C:\Users\jruegg\Desktop\test.py", line 8, in ?
    b = not_existent_variable
NameError: not_existent_variable
4

1 に答える 1

10

これは

except Exception, e:

Python 1および2の場合(asPython 2.6および2.7でも機能します)。

(一体なぜ1.5.2を使用しているのですか!?)

次に、使用するエラーのタイプを取得しますtype(e)。使用しているPython2で型名を取得するにはtype(e).__name__、1.5.2で機能するかどうかわかりません。ドキュメントを確認する必要がありますが、

更新:そうではありませんでしたが、e.__class__.__name__しました。

于 2010-12-16T08:35:20.573 に答える