1.错误处理
使用try except finally
try: i = 10/0 except ZeroDivisionError, e: print "ZeroDivisionError", e finally: print "Finally"
ZeroDivisionError integer division or modulo by zero Finally
错误类型(含warning)
BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StandardError | +-- BufferError | +-- ArithmeticError | | +-- FloatingPointError | | +-- OverflowError | | +-- ZeroDivisionError | +-- AssertionError | +-- AttributeError | +-- EnvironmentError | | +-- IOError | | +-- OSError | | +-- WindowsError (Windows) | | +-- VMSError (VMS) | +-- EOFError | +-- ImportError | +-- LookupError | | +-- IndexError | | +-- KeyError | +-- MemoryError | +-- NameError | | +-- UnboundLocalError | +-- ReferenceError | +-- RuntimeError | | +-- NotImplementedError | +-- SyntaxError | | +-- IndentationError | | +-- TabError | +-- SystemError | +-- TypeError | +-- ValueError | +-- UnicodeError | +-- UnicodeDecodeError | +-- UnicodeEncodeError | +-- UnicodeTranslateError +-- Warning +-- DeprecationWarning +-- PendingDeprecationWarning +-- RuntimeWarning +-- SyntaxWarning +-- UserWarning +-- FutureWarning +-- ImportWarning +-- UnicodeWarning +-- BytesWarning
logging模块记录错误信息
import logging def Test(i): try: j = 10/i except StandardError, e: print "standardError" logging.exception(e) print "Test" Test(0) print "End"
standardError ERROR:root:integer division or modulo by zero Test End Traceback (most recent call last): File "F:/PyProject/test2.py", line 9, in Test j = 10/i ZeroDivisionError: integer division or modulo by zero
自定义错误类型继承内置错误类型
class FooError(StandardError):
pass
def foo(s):
n = int(s)
if n == 0:
raise FooError("value is %s" % s)
foo("0")
Traceback (most recent call last): File "F:/PyProject/test2.py", line 18, in <module> foo("0") File "F:/PyProject/test2.py", line 15, in foo raise FooError("value is %s" % s) __main__.FooError: value is 0
另 可以在except中捕获错误之后 使用 raise 将错误抛给顶层调用者去处理
2.调试
assert 断言
def foo(n): i = int(n) assert i != 0, "catch assert" return i a = foo("0") print a
Traceback (most recent call last): File "F:/PyProject/test2.py", line 13, in <module> a = foo("0") File "F:/PyProject/test2.py", line 10, in foo assert i != 0, "catch assert"
AssertionError: catch assert
相当于 if i != 0 为True 继续执行 反之 抛出 AssertionError并中断运行
关闭assert方法 是 在python 解释器中加参数 -O 来将python编译成pyo文件
logging不会抛出错误 但是会打日志 默认logging级别是WARNING 通过logging.basicConfig(level=logging.日志等级)修改默认值
logging模块将日志打印到了标准输出中,且只显示了大于等于设定级别的日志 (日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG >NOTSET)
默认格式为 Logger:输出内容
启动Python的调试器pdb,让程序以单步方式运行,可以随时查看运行状态
以参数-m pdb
启动程序后,pdb定位到下一步要执行的代码。输入命令l
来查看代码。任何时候都可以输入命令p 变量名
来查看变量。
pdb.set_trace() 这个方法也是用pdb,但是不需要单步执行,我们只需要import pdb
,然后,在可能出错的地方放一个pdb.set_trace()
,就可以设置一个断点,行代码,程序会自动在pdb.set_trace()
暂停并进入pdb调试环境,可以用命令p
查看变量,或者用命令c
继续运行