try:
something here
except:
print('the whatever error occurred.')
如何在我的except:
块中打印错误/异常?
#1楼
如果您要传递错误字符串,请参见以下来自错误和异常 (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
#2楼
对于Python 2.6和更高版本以及Python 3.x:
except Exception as e: print(e)
对于Python 2.5及更早版本,请使用:
except Exception,e: print str(e)
#3楼
traceback
模块提供了格式化和打印异常及其追溯的方法,例如,这将像默认处理程序那样打印异常:
import traceback
try:
1/0
except Exception:
traceback.print_exc()
输出:
Traceback (most recent call last):
File "C:\scripts\divide_by_zero.py", line 4, in <module>
1/0
ZeroDivisionError: division by zero
#4楼
如果您要这样做,可以使用assert语句来完成一次线性错误提升。 这将帮助您编写可静态修复的代码并及早检查错误。
assert type(A) is type(""), "requires a string"
#5楼
在Python 2.6或更高版本中,它更干净一些:
except Exception as e: print(e)
在旧版本中,它仍然很可读:
except Exception, e: print e
#6楼
(我打算将其作为对@jldupont答案的评论,但是我没有足够的声誉。)
我在其他地方也看到过类似@jldupont的答案的答案。 FWIW,我认为必须注意以下几点:
except Exception as e:
print(e)
默认情况下会将错误输出打印到sys.stdout
。 通常,更合适的错误处理方法是:
except Exception as e:
print(e, file=sys.stderr)
(请注意,必须import sys
才能import sys
起作用。)这样,错误将STDOUT
到STDERR
而不是STDOUT
,这允许正确的输出解析/重定向/等。 我知道问题完全是关于“打印错误”的,但是在此处指出最佳实践而不是忽略可能导致最终学习不到的标准代码的细节似乎很重要。
我没有在Cat Plus Plus的答案中使用过traceback
模块,也许这是最好的方法,但是我想我应该把它扔在那里。
#7楼
如果要将消息打印到stderr,请以状态代码1(错误)退出:
import sys
try:
...
except Exception as e:
sys.exit("Message to print to stderr")