抛出异常——优雅的处理错误
def boxPrint(symbol, wight, height):
if len(symbol) != 1:
raise Exception('symbol must be a single character string.')
if wight <= 2:
raise Exception('Wight must be greater 2.')
if height <= 2:
raise Exception('Height must be greater 2.')
print(symbol * wight)
for i in range(height - 2):
print(symbol + (weight - 2) * ' ' + symbol)
print(symbol * weight)
for sym, w, h in (('*', 4, 4)('i', 1, 2)('ZZ', 3, 3)):
try:
boxPrint(sym, w, h)
except Exception as err:
print('An error happend: ' + err)
取得反向跟踪的字符串
调用栈:函数调用的序列
traceback.format_exc()
函数获取反向跟踪信息的字符串形式。
import traceback
try:
raise Exception('This is the error message.')
except:
errorFile = open('errorInfo.txt', 'w')
errorFile.write(traceback.format_exc())
errorFile.close()
print('The traceback info was written into errorInfo.txt.'
断言
……
日志
……
Reference:python编程快速上手