# 异常的抛出机制: # # 1、如果在运行时发生异常,解释器会查找相应的处理语句(称为handler). # # 2、要是在当前函数里没有找到的话,它会将异常传递给上层的调用函数,看看那里能不能处理。 # # 3、如果在最外层(全局“main”)还是没有找到的话,解释器就会退出,同时打印出traceback以便让用户找到错误产生的原因 # s1 = 'hello' # try: # int(s1) # except IndexError as e: # print(e) # except KeyError as e: # print(e) # except ValueError as e: # print(e) # #except Exception as e: # # print(e) # else: # print('try内代码块没有异常则执行我') # finally: # print('无论异常与否,都会执行该模块,通常是进行清理工作') # 未捕获到异常,程序直接报错 #part2:异常类只能用来处理指定的异常情况,如果非指定异常则无法处理。 # s1 = 'hello' # try: # int(s1) # except IndexError as e: # print (e) #多分支 # s1 = 'hello' # try: # int(s1) # except IndexError as e: # print(e) # except KeyError as e: # print(e) # except ValueError as e: # print(e) #万能异常 在python的异常中,有一个万能异常:Exception,他可以捕获任意异常,即: # s1 = 'hello' # try: # int(s1) # except Exception as e: # print(e) #如果你想要的效果是,对于不同的异常我们需要定制不同的处理逻辑,那就需要用到多分支了 # s1 = 'hello' # try: # int(s1) # except IndexError as e: # print(e) # except KeyError as e: # print(e) # except ValueError as e: # print(e) # s1 = 'hello' # try: # int(s1) # except IndexError as e: # print(e) # except KeyError as e: # print(e) # except ValueError as e: # print(e) # except Exception as e: # print(e) # try...finally... # # try...finally...子句用来表达这样的情况: # # 我们不管线捕捉到的是什么错误,无论错误是不是发生,这些代码“必须”运行,比如文件关闭,释放锁,把数据库连接返还给连接池等。 #异常的其他机构 # s1 = 'hello' # try: # int(s1) # except IndexError as e: # print(e) # except KeyError as e: # print(e) # except ValueError as e: # print(e) # #except Exception as e: # # print(e) # else: # print('try内代码块没有异常则执行我') # finally: # print('无论异常与否,都会执行该模块,通常是进行清理工作') #主动触发异常:又称抛出异常 # __author__ = 'Linhaifeng' # # try: # raise TypeError('类型错误') # except Exception as e: # print(e) # class EgonException(BaseException): # def __init__(self,msg): # self.msg=msg # def __str__(self): # return self.msg # # try: # raise EgonException('类型错误') # except EgonException as e: # print(e) #try..except的方式比较if的方式的好处 #try..except这种异常处理机制就是取代if那种方式,让你的程序在不牺牲可读性的前提下增强健壮性和容错性 #异常处理中为每一个异常定制了异常类型(python中统一了类与类型,类型即类),对于同一种异常,一个except就可以捕捉到,可以同时处理多段代码的异常(无需‘写多个if判断式’)减少了代码,增强了可读性 # 使用try..except的方式 # # 1:把错误处理和真正的工作分开来 # 2:代码更易组织,更清晰,复杂的工作任务更容易实现; # 3:毫无疑问,更安全了,不至于由于一些小的疏忽而使程序意外崩溃了; #什么时候用异常处理 #y...except应该尽量少用,因为它本身就是你附加给你的程序的一种异常处理的逻辑,与你的主要的工作是没有关系的 #这种东西加的多了,会导致你的代码可读性变差 #只有在有些异常无法预知的情况下,才应该加上try...except,其他的逻辑错误应该尽量修正