try:
something here
except:
print 'the whatever error occurred.'
except:
ブロックでエラーを印刷するにはどうすればよいですか?あなたはここで、エラー文字列を渡したい場合はPythonでエラーを出力するには?
try:
something here
except:
print 'the whatever error occurred.'
except:
ブロックでエラーを印刷するにはどうすればよいですか?あなたはここで、エラー文字列を渡したい場合はPythonでエラーを出力するには?
からの例です:
はPython 2.5およびそれ以前についてはexcept Exception as e: print(e)
、使用:
except Exception,e: print str(e)
OPが望むものに最も近いと思われます。 – physicsmichael
'str()'部分は冗長です - 'print e'は' print str(e) '[[print'はそれ自身の文字列化を行います]]とまったく同じものです。 –
@alex:スローされた例外のサブクラス(もしあれば)に依存しませんか? __str__が持つ可能性がある間に、__repr__メソッドが実装されていない可能性があります。いずれにしても、不完全な実装の良い代替手段はありません;-) – jldupont
はErrors and Exceptions(Pythonの2.6)はPython 2.6以降については
>>> try:
... raise Exception('spam', 'eggs')
... except Exception as inst:
... print type(inst) # the exception instance
... print inst.args # arguments stored in .args
... print inst # __str__ allows args to printed directly
... x, y = inst # __getitem__ allows args to be unpacked directly
... print 'x =', x
... print 'y =', y
...
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
非常に完全ですが、「as」はPython 2.6より前には動作しません。 – foosion
traceback
モジュールは、フォーマットと印刷の方法を提供します例外とそれらのトレースバック、例えば。
except: traceback.print_exc()
これは正解です –
@ KarthikTと正解です。 –
あなたがしたいことがあれば、アサート文で1つのエラーエラーを発生させることができます。これにより、静的に修正可能なコードを記述し、エラーを早期にチェックするのに役立ちます。 はPython 2.6以上で
assert type(A) is type(""), "requires a string"
それは少しクリーナーです:それはまだ非常に読みやすいです古いバージョンでは
except Exception as e: print(e)
:
except Exception, e: print e
python3では、 "as"で1番目の方法を使用する必要があります。 –
私はタイトルを変え勧め:あなたは、印刷されていません__error__、あなたは__exception__を出力しています。それらは違う。 – FaithReaper