当程序出错时,python会自动触发异常,也可以通过raise语句触发异常;一旦执行了raise语句,之后的语句不再执行;但如果加入了try...excepet...finally语句,except里的语句会被执行,finally一样也会被执行。
raise语法格式:raise [Exception [, args [, traceback]]],参数Exception 是异常的类型数标准异常中任一种(如NameError),args 是自已提供的异常参数;参数traceback可选,是跟踪异常对象。
raise 语句有如下三种常用的用法:
单独raise,不加其他参数。在except语句中,引发当前上下文中捕获异常,或默认引发RuntimeError。通俗理解就是,捕捉到了异常,但是又想重新引发它,即传递异常不进行处理,可以调用不带参数的raise。 # 在except语句中使用raise try: s = 'a' if not s.isdigit(): raise ValueError("s must be a number!") except ValueError as e: print("引发异常:", e) raise # 结果 ''' Traceback (most recent call last): File "C:/../../../test.py", line 13, in <module> raise ValueError("s must be a number!") ValueError: s must be a number! ''' # 在没有引发过异常的程序使用raise,引发的是默认的RuntimeError try: s = 'a' if not s.isdigit(): raise except RuntimeError as e: print("引发异常:", e) # 结果 ''' 引发异常: No active exception to reraise ''' raise 异常类名称:raise后面带一个异常类名称,表示引发执行类型的异常。 try: s = None if s is None: print('s是空对象') raise ValueError print(len(s)) except Exception: print('空对象没有长度') # 结果 ''' s是空对象 空对象没有长度 ''' raise 异常类名称("描述信息"):在引发指定类型的异常,同时附带异常的描述信息。 # 定义函数 def func(number): print(number) if number < 1: raise Exception("Invalid number!") # 触发异常后,后面的代码不会执行 print(number + 1) if __name__ == '__main__': try: func(0) except Exception as e: print("触发了异常!", e) else: print("未触发异常!") finally: print("程序执行完毕!") # 结果 ''' 0 触发了异常! Invalid number! 程序执行完毕! '''