2009-09-27 3 views
249
try: 
    something here 
except: 
    print 'the whatever error occurred.' 

except:ブロックでエラーを印刷するにはどうすればよいですか?あなたはここで、エラー文字列を渡したい場合はPythonでエラーを出力するには?

+0

私はタイトルを変え勧め:あなたは、印刷されていません__error__、あなたは__exception__を出力しています。それらは違う。 – FaithReaper

答えて

352

からの例です:

はPython 2.5およびそれ以前については
except Exception as e: print(e) 

、使用:

except Exception,e: print str(e) 
+1

OPが望むものに最も近いと思われます。 – physicsmichael

+18

'str()'部分は冗長です - 'print e'は' print str(e) '[[print'はそれ自身の文字列化を行います]]とまったく同じものです。 –

+4

@alex:スローされた例外のサブクラス(もしあれば)に依存しませんか? __str__が持つ可能性がある間に、__repr__メソッドが実装されていない可能性があります。いずれにしても、不完全な実装の良い代替手段はありません;-) – jldupont

31

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 
+3

非常に完全ですが、「as」はPython 2.6より前には動作しません。 – foosion

160

tracebackモジュールは、フォーマットと印刷の方法を提供します例外とそれらのトレースバック、例えば。

except: traceback.print_exc() 
+21

これは正解です –

+0

@ KarthikTと正解です。 –

2

あなたがしたいことがあれば、アサート文で1つのエラーエラーを発生させることができます。これにより、静的に修正可能なコードを記述し、エラーを早期にチェックするのに役立ちます。 はPython 2.6以上


assert type(A) is type(""), "requires a string" 

145

それは少しクリーナーです:それはまだ非常に読みやすいです古いバージョンでは

except Exception as e: print(e) 

except Exception, e: print e 
+10

python3では、 "as"で1番目の方法を使用する必要があります。 –

関連する問題