您所在的位置:开发 > Web > Python > Python异常处理体系简介(1)

Python异常处理体系简介(1)

2009-02-25 10:34 biansutao javaeye 我要评论(0) 字号:T | T
一键收藏,随时查看,分享好友!

Python的异常处理能力是很强大的,可向用户准确反馈出错信息。本文将对Python异常处理体系进行简单介绍。

AD:

Python内建异常体系结构

The class hierarchy for built-in exceptions is:

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

捕获异常的方式

方法一:捕获所有的异常

  ''' 捕获异常的第一种方式,捕获所有的异常 '''
    try:
        a = b
        b = c
    except Exception,data:
        print Exception,":",data
    '''输出:<type 'exceptions.Exception'> : local variable 'b' 
referenced before assignment ''

方法二:采用traceback模块查看异常,需要导入traceback模块

   ''' 捕获异常的第二种方式,使用traceback查看异常 '''
try:
a = b
b = c
except:
print traceback.print_exc()
'''输出: Traceback (most recent call last):
File "test.py", line 20, in main
a = b
UnboundLocalError: local variable 'b' referenced before assignmen

方法三:采用sys模块回溯最后的异常

''' 捕获异常的第三种方式,使用sys模块捕获异常 '''
try:
a = b
b = c
except:
info = sys.exc_info()
print info
print info[0]
print info[1]
'''输出:
(<type 'exceptions.UnboundLocalError'>, UnboundLocalError("local
variable 'b' referenced before assignment",),
<traceback object at 0x00D243F0>)
<type 'exceptions.UnboundLocalError'>
local variable 'b' referenced before assignment
'''

网友评论TOP5

查看所有评论(

提交评论

  1. 什么是响应式Web设计?
  2. Java路线图:甲骨文的两年计划

热点专题

更多>>

读书

数据库加密——最后的防线
本书是关于如何使用已有的密码技术和算法对数据库中存储的信息进行保护的书,书中所关注的内容主要是如何设计、建立(或者挑选、

51CTO旗下网站

领先的IT技术网站 51CTO 领先的中文存储媒体 WatchStor 中国首个CIO网站 CIOage 中国首家数字医疗网站 HC3i 移动互联网生活门户 灵客风LinkPhone