| 
 一、什么是异常?  
异常即是一个事件,该事件会在程序执行过程中发生,影响了程序的正常执行。  
一般情况下,在Python无法正常处理程序时就会发生一个异常。  
异常是Python对象,表示一个错误。  
当Python脚本发生异常时我们需要捕获处理它,否则程序会终止执行。 常见异常  
# AttributeError 调用不存在的方法引发的异常 # EOFError 遇到文件末尾引发的异常 # ImportError 导入模块出错引发的异常 # IndexError 列表月越界引发的异常 # IOError I/O操作引发的异常,如打开文件出错等 # KeyError 使用字典中不存在的关键字引发的异常 # NameError 使用不存在的变量名引发的异常 # TabError 语句块缩进不正确引发的异常 # ValueError 搜索列表中不存在值引发的异常 # ZeroDivisionError 除数为零引发的异常 1 2 3 4 5 6 7 8 9 10 二、基础异常处理  
捕捉异常可以使用try/except语句,见下例子。  
try/except语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理。  
如果你不想在异常发生时结束你的程序,只需在try里捕获它。  
try的工作原理是,当开始一个try语句后,python就在当前程序的上下文中作标记,这样当异常出现时就可以回到这里,try子句(与try同级的except等)先执行,接下来会发生什么依赖于执行时是否出现异常。  
如果当try后的语句执行时发生异常,python就跳回到try并执行第一个匹配该异常的except子句,异常处理完毕,控制流就通过整个try语句(除非在处理异常时又引发新的异常)。  
如果在try后的语句里发生了异常,却没有匹配的except子句,异常将被递交到上层的try,或者到程序的最上层(这样将结束程序,并打印缺省的出错信息)。  
如果在try子句执行时没有发生异常,python将执行else语句后的语句(如果有else的话),然后控制流通过整个try语句。  
不管在try有无异常抛出时都会执行本级try对应的finally。  
基础语法  
try:  检测异常代码段 except:  发生异常后执行代码段 else:  未发生异常执行代码段 finally:  最终执行代码段  
1 2 3 4 5 6 7 8 9 例子:  
print("test1") try:  s = input()  if s is None:  print ("s 是空对象")  print(len(s)) #这句抛出异常  except TypeError:  print("类型错误空对象没有长度") else:  print("no problem") finally:  print('end test1') 1 2 3 4 5 6 7 8 9 10 11 12  
 print("test1") try:  s = None  if s is None:  print ("s 是空对象")  print(len(s)) #这句抛出异常  except TypeError:  print("类型错误空对象没有长度") else:  print("no problem") finally:  print('end test1') 1 2 3 4 5 6 7 8 9 10 11 12  
 三、捕获异常的操作  
为了能够捕获异常,"except"语句必须有用相同的异常来抛出类对象或者字符串。  
3.1 使用except而不带任何异常类型  
你可以不带任何异常类型使用except,如下实例以上方式try-except语句捕获所有发生的异常。但这不是一个很好的方式,我们不能通过该程序识别出具体的异常信息。因为它捕获所有的异常。  
print("test2")  try:  x = 1  y = 0  z= x/y except:#捕获所有异常  print('there is problem') else:  print('no problem') finally:  print('end test2') 1 2 3 4 5 6 7 8 9 10 11  
 3.2使用except而带多种异常类型  
你也可以使用相同的except语句来处理多个异常信息,这些异常将被放在一个括号里成为一个元组,如下所示:  
try:  正常的操作 except(Exception1[, Exception2[,...ExceptionN]]]):  发生以上多个异常中的一个,执行这块代码 else:  如果没有异常执行这块代码 1 2 3 4 5 6 print('test3') try:  x = 1  y = 0  z= x/y except (NameError,ZeroDivisionError):  print("problem is (NameError,ZeroDivisionError)") except (RuntimeError, TypeError):  print("problem is (RuntimeError, TypeError)") except:  print("problem")  raise else:  print("no problem") finally:  print('end test3') 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16  
 最后一个except子句可以忽略异常的名称,它将被当作通配符使用。你可以使用这种方法打印一个错误信息,然后再次把异常抛出。  
import sys try:  f = open('myfile.txt')  s = f.readline()  i = int(s.strip()) # except OSError as err: # print("OS error: {0}".format(err)) except ValueError:  print("Could not convert data to an integer.") except:  print("Unexpected error:", sys.exc_info()[0])  for i in sys.exc_info():  print(i)  raise Exception('line xxx') finally:  print("end") 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16  
注意有多个expect的时候会首先执行第一个能被捕获到的异常并且只执行一个  
3.3使用多层try的时候except的传递  
多重异常的处理  
可以在try语句中嵌套另一个try语句  
一旦发生异常,python匹配最近的except语句,  
若是内部except能够处理该异常,则外围try语句不会捕获异常。  
若是不能,或者忽略,外围try处理  
内层异常捕获失败执行内层finally跳出外层执行异常捕获  
try:  try:  x = 1  y = 0  z= x/y  except NameError:  print ("NameError")  finally:  print ("Finally inside") except :  print ("All exception outside") finally:  print ("Finally outside") 1 2 3 4 5 6 7 8 9 10 11 12 13  
 try:  try:  x = 1  y = 0  z= x/y  except ZeroDivisionError:  print ("ZeroDivisionError")  finally:  print ("Finally inside") except :  print ("All exception outside") else:  print ("No exception outside") finally:  print ("Finally outside") 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 内层捕获成功执行expect finally 执行外层else finally  
   
四、自己抛出异常  
触发异常时候,我们可以使用raise语句自己触发异常。raise 唯一的一个参数指定了要被抛出的异常。它必须是一个异常的实例或者是异常的类(也就是 Exception 的子类)。  
如果你只想知道这是否抛出了一个异常,并不想去处理它,那么一个简单的 raise 语句就可以再次把它抛出。  
raise语法格式如下:  
raise [Exception [, args [, traceback]]] 1 语句中 Exception 是异常的类型,参数标准异常中任一种,args 是自已提供的异常参数。最后一个参数是可选的(在实践中很少使用),如果存在,是跟踪异常对象。  
print("test4") try:  s = None  if s is None:  print ("s 是空对象")  raise NameError #如果引发NameError异常,后面的代码将不能执行  print(len(s)) #这句不会执行,但是后面的except还是会走到 except TypeError:  print("类型错误空对象没有长度") except NameError:  print("接收到raise的异常NameError") finally:  print('end test4') 1 2 3 4 5 6 7 8 9 10 11 12 13  
 抛出异常时候的参数附加显示  
print("test5") def mye( level ):  if level < 1:  raise Exception(str(level) + " is Invalid level!")  # 触发异常后,后面的代码就不会再执行 try:  mye(0) # 触发异常 except Exception as err:  print(Exception)  print(type(err))  print(err) else:  print("successfully") finally:  print('end test5') 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15  
 五、异常信息的详细处理打印  
使用sys模块可以将异常详细信息打印出来  
import sys try:  x = 1  y = 0  z= x/y except :  t, v, tb = sys.exc_info()  print(t)  print(v)  print(tb) 1 2 3 4 5 6 7 8 9 10  
 捕获异常后间接答应  
def temp_convert(var):  try:  return int(var)  except ValueError as e:  print (ValueError)  print (e )  
# 调用函数 temp_convert("xyz")  
1 2 3 4 5 6 7 8 9 10  
 六、创建自己的异常  
一个异常可以是一个字符串,类或对象。 Python的内核提供的异常,大多数都是实例化的类,这是一个类的实例的参数。  
通过创建一个新的异常类,程序可以命名它们自己的异常。异常应该是典型的继承自Exception类,通过直接或间接的方式。你可以通过创建一个新的异常类来拥有自己的异常。异常类继承自 Exception 类。  
在这个例子中,类 Exception 默认的 __init__() 被覆盖。  
#自定义异常 class LengthRequiredException(Exception):  def __init__(self,length,minLength):  Exception.__init__(self)  self.length = length  self.minLength = minLength  
#引发自定义的异常 l = [1,2,3,4,5] minLength = 6 try:  raise LengthRequiredException(len(l),minLength) except IndexError:  print("index out of bounds") except LengthRequiredException as e:  print("Length not fit :length is %d required %d" %(e.length,e.minLength)) else:  print("no exception was raised") finally:  print("finally will be execute") 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20  
 class OutOfRangeException(Exception):  def __init__(self,errMsg):  self.msg = errMsg  def __str__(self):  return self.msg class Person(object):  def __init__(self):  self.name = None  self.age = None  def setAge(self,age):  if age < 0 or age > 100:  raise OutOfRangeException("年龄应该在0-100之间!")  self.age = age  def setName(self,name):  self.name = name  def __str__(self):  return "name:{} age:{}".format(self.name,self.age) person = Person() person.setName("Edward") person.setAge(80) print(person) try:  person.setAge(101) except OutOfRangeException as ex:  print(ex)  
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26  
 当创建一个模块有可能抛出多种不同的异常时,一种通常的做法是为这个包建立一个基础异常类,然后基于这个基础类为不同的错误情况创建不同的子类:  
class Error(Exception):  """Base class for exceptions in this module."""  pass   class InputError(Error):  """Exception raised for errors in the input.    Attributes:  expression -- input expression in which the error occurred  message -- explanation of the error  """    def __init__(self, expression, message):  self.expression = expression  self.message = message   class TransitionError(Error):  """Raised when an operation attempts a state transition that's not  allowed.    Attributes:  previous -- state at beginning of transition  next -- attempted new state  message -- explanation of why the specific transition is not allowed  """    def __init__(self, previous, next, message):  self.previous = previous  self.next = next  self.message = message 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 七、常用模块  
同样的例子也可以写成如下方式:  
try:  fh = open("testfile", "w")  try:  fh.write("这是一个测试文件,用于测试异常!!")  finally:  print "关闭文件"  fh.close(http://www.my516.com) except IOError:  print "Error: 没有找到文件或读取文件失败" 1 2 3 4 5 6 7 8 9 当在try块中抛出一个异常,立即执行finally块代码。  
finally块中的所有语句执行后,异常被再次触发,并执行except块代码。  
参数的内容不同于异常。 --------------------- 
 
   |