[入门-8] 错误处理之异常

来源:互联网 发布:openwrt 修改mac wifi 编辑:程序博客网 时间:2024/06/01 10:30

常见异常Error

  • NameError
  • ZeroDivisionError
  • SyntaxError(唯一非运行时错误)
  • IndexError
  • KeyError
  • IOErrpr
  • OSError
  • AttributeError
  • ValueError
  • TypeError

两个不是由错误引起的异常Error:

  • SystemExit python程序需要退出
  • KeyboardInterupt ctrl+C

异常类

  • BaseExceptiom
    • KeyboardInterrupt
    • SystemExit
    • Exception
      • all other current build-in exceptions
try:    passexcept ValueError, reason:    print "%s" %str(reason)except TypeError, reason:    print "%s" %str(reason)except (IndexError, KeyError), reason:    print "%s" %str(reason)except Exception, reason:  #捕获所有异常, 不推荐使用空的except语句    print "%s" %str(reason)else:  #try 中没有异常的时候会执行else    print "No exceptions in try block"finally:  #无论如何都会执行到的代码,既是否有异常出现,都会执行    pass

触发异常

raise SomeException, args, tracebackraise exclass, args, tbraise exclass()raise exclass, instanceraise string, args, tb

断言

#assert = raise if not ...#AssertError,断言引发的异常asssert expression, argumentsassert 1==1try:    passexcept AssertionError, args:    print '%s, %s' %(args.__class__.__name__, args)       

sys模块

try:    passexception:    import sys    exc_tuple = sys.exc_info()print exc_tuplefor item in exc_tuple:    print item#(exc_type, exc_value, exc_traceback) = sys.exc_info()#异常类,类实例,追踪记录对象

Reference

Python核心编程

0 0