python异常处理整理

来源:互联网 发布:hold the door知乎 编辑:程序博客网 时间:2024/05/22 17:50
# 自定义异常类,采用基本异常类继承class Test_case_error(Exception):passdef hello(filename):    if filename == 'hello':        raise NameError('input name error')    if filename == 'haha':        raise KeyError('can\'t pharse number')    if filename == 'exception':        raise Exception('you can try it')    if filename == '1':        raise Test_case_error('hahahha')# try 中抛出的异常由except 来处理,由except处理异常后,程序不会中断会继续执行try:    hello(filename)except Test_case_error:    print('hello')# 通过标识打开和关闭异常处理,可使用raise 主动抛出异常class MuffledCalculator:    def __init__(self,muffled):        self.muffled = muffled    def calc(self,expr):        try:            hello(expr)        except Test_case_error:            if self.muffled:                print('I can do it!')            else:                raise# 打开异常处理test_Exception = MuffledCalculator(True)test_Exception.calc('1')# 关闭异常处理test_Exception = MuffledCalculator(False)test_Exception.calc('1')# 多个except处理子句class MuffledCalculator:    def __init__(self,muffled):        self.muffled = muffled    def calc(self,expr):        try:            hello(expr)        except Test_case_error:            if self.muffled:                print('I can do it!')            else:                raise        except NameError:            print('The name ERROR!')# 上面的简化版class MuffledCalculator:     def __init__(self,muffled):         self.muffled = muffled     def calc(self,expr):         try:             hello(expr)         except Test_case_error:             if self.muffled:                  print('I can do it!')             else:                 raise             except NameError:                 print('The name ERROR!')# 捕捉对象,期望发生异常时程序继续运行但异常信息同时也需要输出filename = 'haha'try:    hello(filename)except KeyError as e:    print(e)print('The programmer is still continue')# 捕捉所有异常,可采用在except后不跟任何异常filename = 'haha'try:    hello(filename)except:    print('Something wrong happen!')# 加入else子句实现循环的处理问题# 如下实例,只有在无异常时才会退出循环while True:    try:        x = input('X:')        y = input('Y:')        value = x/y        print ('x/y is' ,value)    except:        print('Invalid input,Try again!')    else:        break# finally 子句,用来在可能的异常后进行清理,一下实例,不管是否有异常finally子句都会被执行x = Nonetry:    x = 1/0finally:    print('cleaning up!')    del(x)# 本例中如果不对x的赋值做清除, x将有于异常的存在一直无法赋值# 让我们尝试下try except else finally兼而有之try:    1/0except:    print('Unknown variable!')else:    print('That went well!')finally:    print('Cleaning up!')# 让异常与函数结合,让你的异常处理更简洁方便;# 如果异常在函数内引发而不被处理,异常将传播到调用该函数的位置,若仍然未被处理将一直到达主程序def faulty():    raise Exception('something is wrong!')def ignore_exception():    faulty()def handle_exception():    try:        faulty()    except:        print('Exception handled')handle_exception()ignore_exception()
原创粉丝点击