8.错误
8.异常

常用异常

更多异常

自定义异常
一、异常处理:
1 AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x 2 IOError 输入/输出异常;基本上是无法打开文件 3 ImportError 无法引入模块或包;基本上是路径问题或名称错误 4 IndentationError 语法错误(的子类) ;代码没有正确对齐 5 IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5] 6 KeyError 试图访问字典里不存在的键 7 KeyboardInterrupt Ctrl+C被按下 8 NameError 使用一个还未被赋予对象的变量 9 SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了) 10 TypeError 传入对象类型与要求的不符合 11 UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量, 12 导致你以为正在访问它 13 ValueError 传入一个调用者不期望的值,即使值的类型是正确的 14 15 常用异常
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 更多异常
1 try:
2 intput = raw_input()
3 data = int(intput)
4 except Exception,e: #e是Exception类的一个对象,调用__str__方法
5 print"请输入数字"
1 #输出sb,输出A类的__str__方法 2 3 class A: 4 def __str__(self): 5 return 'sb' 6 obj = A() 7 print obj 8 9 #自定义错误异常 10 11 class AlexError(Exception): 12 def __init__(self,msg=None): 13 self.message = msg 14 def __str__(self): 15 if self.message: 16 return self.message 17 else: 18 return 'alex error' 19 try: 20 raise AlexError('error') #当有值时,输出值,否则输出alex erroer 21 except Exception,e: 22 print e
----根据武沛齐----整理修改-----