抛出异常
>>> raise Exception('This is the error message')
Traceback (most recent call last):
File "<pyshell#54>", line 1, in <module>
raise Exception('This is the error message')
Exception: This is the error message
如果没有try
和 Exception
用来抛出异常,程序就会崩溃
def boxPrint(symbol,width,height):
if len(symbol) != 1:
raise Exception('Symbol must be a single character string.')
if width <= 2:
raise Exception('Width must be greater than 2.')
if height <= 2:
raise Exception('Height must be greater than 2')
print(symbol * width)
for i in range(height - 2):
print(symbol + ' '*(width - 2) + symbol)
print(symbol * width)
for sym,w,h in (('*',4,4),('0',20,5),('x',1,3),('ZZ',3,3)):
try:
boxPrint(sym,w,h)
except Exception as err:
print('An Exception happend:'+ str(err))
try:
pass
except Exception as e:
raise
else:
pass
finally:
pass
try:
pass
except Exception as e:
raise e
else:
pass
try:
pass
except Exception as e:
raise e
finally:
pass
try:
pass
except Exception as e:
raise e
取得反向跟踪的字符串
#! python3
#errorExample.py
def spam():
func()
def func():
raise Exception('This is the error message')
spam()
“调用栈”,反向跟踪
===================== RESTART: D:/python/errorExample.py =====================
Traceback (most recent call last):
File "D:/python/errorExample.py", line 5, in <module>
spam()
File "D:/python/errorExample.py", line 2, in spam
func()
File "D:/python/errorExample.py", line 4, in func
raise Exception('This is the error message')
Exception: This is the error message
traceback
模块
>>> 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 to errorInfo.txt.')
116
The traceback info was written to errorInfo.txt.
#errorInfo.txt
Traceback (most recent call last):
File "<pyshell#72>", line 2, in <module>
Exception: This is the error message.
断言
日志
import logging
logging.basicConfig (level=logging.DEBUG,format=' %(asctime) s- %(levelname) s- %(message)s' )
logging.debug (' Start of program')
def factorial(n):
logging.debug('Start of factorial(%s%%)' % (n) )
total = 1
for i in range(n + 1):
total*=i
logging.debug(' i is' + str(i) + ',total is' + str(total))
logging.debug( 'End of factorial(%s%%)' % (n))
return total
print(factorial(5) )
logging.debug('End of program')
===================== RESTART: D:\python\factorialLog.py =====================
2018-02-07 16:54:56,376- DEBUG- Start of program
2018-02-07 16:54:56,527- DEBUG- Start of factorial(5%)
2018-02-07 16:54:56,547- DEBUG- i is0,total is0
2018-02-07 16:54:56,565- DEBUG- i is1,total is0
2018-02-07 16:54:56,580- DEBUG- i is2,total is0
2018-02-07 16:54:56,593- DEBUG- i is3,total is0
2018-02-07 16:54:56,613- DEBUG- i is4,total is0
2018-02-07 16:54:56,632- DEBUG- i is5,total is0
2018-02-07 16:54:56,651- DEBUG- End of factorial(5%)
0
2018-02-07 16:54:56,694- DEBUG- End of program
不要用print()
调试
日志级别
描述 | 日志函数 | 级别 |
---|---|---|
DEBUG | logging.debug() | 最低级别。用于小细节。通常只有在诊断问题时,你才会关心这些消息 |
INFO | logging.info() | 用于记录程序中一般事件的信息,或确认一切工作正常 |
WARNING | logging.warning() | 它不会阻止程序的工作,但将来可能会用于表示可能的问题 |
ERROR | logging.error() | 用于记录错误,它导致程序做某事失败 |
CRITICAL | logging.critical() | 最高级别。用于表示致命的错误,它导致或将要导致程字完全停止工作 |
>>> import logging
>>> logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s\n" "%(levelname)s- %(message)s')
>>> logging.debug (' Some debugging details.' )
2018-02-07 17:27:36,672- DEBUG- Some debugging details.
>>> logging.info('The logging module is working.' )
2018-02-07 17:28:09,721- INFO- The logging module is working.
>>> logging.warning('An error message is about to be logged.' )
2018-02-07 17:28:23,338- WARNING- An error message is about to be logged.
>>> logging.error('Anhas occurred.')
2018-02-07 17:28:59,818- ERROR- Anhas occurred.
>>> logging.critical( 'The program is unable to recover! ')
2018-02-07 17:29:38,894- CRITICAL- The program is unable to recover!
禁用日志功能
logging.disable(logging.CRITICAL)
>>> import logging
>>> logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s\n" "%(levelname)s- %(message)s')
>>> logging.debug (' Some debugging details.' )
2018-02-07 17:37:48,995- DEBUG- Some debugging details.
>>> logging.disable(logging.CRITICAL)
>>> logging.info('The logging module is working.' )
>>> logging.warning('An error message is about to be logged.' )
>>> logging.error('Anhas occurred.')
>>> logging.critical( 'The program is unable to recover! ')
将日志记录到文件中
>>> import logging
>>> logging.basicConfig(filename='mylogging.txt',level=logging.DEBUG, format=' %(asctime)s\n" "%(levelname)s- %(message)s')
IDLE的调试器
Debug——>Debugger
Go
程序正常执行到终点,或者到达一个断点
Step
调试器执行下一行的代码,并更新窗口显示的局部变量和全局变量
Over
与Step类似,只是如果下一步的遇到一个函数调用,则全速执行函数后,停下
Out
调试器全速执行代码,知道将前的函数执行完毕
Quit
终止调试
调试一个数字相加的程序
print('First Num:')
First = input()
print('Second Num')
Second = input()
print('Third Num')
Third = input()
print('The sum is' + First + Second + Third)
================== RESTART: D:\python\buggyAddingProgram.py ==================
First Num:
20
Second Num
30
Third Num
40
The sum is203040
[DEBUG ON]
断点
代码鼠标右键,set Breakpoint