python异常处理整理

xiaoxiao2021-02-28  129

# 自定义异常类,采用基本异常类继承 class Test_case_error(Exception):pass def 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 = None try: x = 1/0 finally: print('cleaning up!') del(x) # 本例中如果不对x的赋值做清除, x将有于异常的存在一直无法赋值 # 让我们尝试下try except else finally兼而有之 try: 1/0 except: 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()
转载请注明原文地址: https://www.6miu.com/read-80790.html

最新回复(0)