码迷,mamicode.com
首页 > 编程语言 > 详细

python异常处理

时间:2014-09-11 23:43:32      阅读:318      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   数据   div   sp   

1. 内建异常类

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

2. 手动触发异常

raise <异常类>

raise <异常类> , <附加数据>

assert <条件表达式>, <附加数据>  如果条件表达式为假,则抛出异常

3. 自定义异常类

 1 #-*- coding: utf-8 -*-
 2 
 3 #自定义异常类
 4 class AuditException(Exception):
 5     def __init__(self, data):
 6         self.data = data
 7 
 8     def __str__(self):
 9         return self.data
10 
11 
12 
13 if __name__ == "__main__":
14     try:
15         raise AuditException, "The audit operation is not exist."
16     except AuditException, data:
17         print data #The audit operation is not exist.
18 
19     #或者
20 
21     try:
22         raise AuditException, "The audit operation is not exist."
23     except:
24         import traceback
25         traceback.print_exc()
26         

4. 处理异常方式

try/except/else

try:
    #do something
except:
    #如果引发了异常,do something
else:
    #如果未发生异常,do something

try/finally

try:
    #do something
finally:
    #不管有没有异常,do something

 

python异常处理

标签:style   blog   color   io   os   ar   数据   div   sp   

原文地址:http://www.cnblogs.com/zhouwenhong/p/3967424.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!