首页 > 代码库 > python异常处理
python异常处理
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 =http://www.mamicode.com/ data 7 8 def __str__(self): 9 return self.data10 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 traceback25 traceback.print_exc()26
4. 处理异常方式
try/except/else
try: #do somethingexcept: #如果引发了异常,do somethingelse: #如果未发生异常,do something
try/finally
try: #do somethingfinally: #不管有没有异常,do something
python异常处理
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。