异常处理

简单异常捕捉

def f():
    try:
       tem=aaa
    except Exception as e:
        print(e)

f()
AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
IOError 输入/输出异常;基本上是无法打开文件
ImportError 无法引入模块或包;基本上是路径问题或名称错误
IndentationError 语法错误(的子类) ;代码没有正确对齐
IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
KeyError 试图访问字典里不存在的键
KeyboardInterrupt Ctrl+C被按下
NameError 使用一个还未被赋予对象的变量
SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)
TypeError 传入对象类型与要求的不符合
UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,
导致你以为正在访问它
ValueError 传入一个调用者不期望的值,即使值的类型是正确的

常用异常
常见错误
 1 ArithmeticError
 2 AssertionError
 3 AttributeError
 4 BaseException
 5 BufferError
 6 BytesWarning
 7 DeprecationWarning
 8 EnvironmentError
 9 EOFError
10 Exception
11 FloatingPointError
12 FutureWarning
13 GeneratorExit
14 ImportError
15 ImportWarning
16 IndentationError
17 IndexError
18 IOError
19 KeyboardInterrupt
20 KeyError
21 LookupError
22 MemoryError
23 NameError
24 NotImplementedError
25 OSError
26 OverflowError
27 PendingDeprecationWarning
28 ReferenceError
29 RuntimeError
30 RuntimeWarning
31 StandardError
32 StopIteration
33 SyntaxError
34 SyntaxWarning
35 SystemError
36 SystemExit
37 TabError
38 TypeError
39 UnboundLocalError
40 UnicodeDecodeError
41 UnicodeEncodeError
42 UnicodeError
43 UnicodeTranslateError
44 UnicodeWarning
45 UserWarning
46 ValueError
47 Warning
48 ZeroDivisionError
49 
50 更多异常
更多错误

其它格式

try:
    # 主代码块
    pass
except KeyError,e:
    # 异常时,执行该块
    pass
else:
    # 不触发except KeyError,e:的时候就执行这句
    pass
finally:
    # 无论异常与否,最终执行该块
    pass

主动触发错误

1 def f():
2     try:
3        print(123)
4        raise Exception("chu cuo le ")
5     #这里捕捉一下主动触发错误
6     except Exception as e:
7         print(e)
8 
9 f()
View Code

主动触发原理

class f1:
    def __init__(self,error):
        self.error=error
    def __str__(self):
        return self.error

f=f1("chu cuo le ")
print(f)

#是不是跟  raise Exception() 很像
结果:
chu cuo le 

自定义异常

#继承Exception类
class div_error(Exception):

    def __init__(self, msg):
        self.message = msg

    def __str__(self):
        return self.message

try:
    raise div_error('我的异常')
except div_error,e:
    print e

结果:
我的异常

断言

这个很少用测试代码的时候可能会用到

# assert 条件
 
assert 1 == 1
 
assert 1 == 2
原文地址:https://www.cnblogs.com/menkeyi/p/6777583.html