本系列随笔是本人的学习笔记,初学阶段难免会有理解不当之处,错误之处恳请指正。转载请注明出处:https://www.cnblogs.com/itwhite/p/12299739.html。
Python 中的异常处理有许多与 C++ 中类似的部分,比如 raise 语句与 C++ 中的 throw 语句相似, try-except 语句与 C++ 中的 try-catch 语句相似。
当然也有一些不同的地方,比如:Python 中可以捕获“除数为0”这种运行时错误,而 C++ 就不能,例如:
x = int(input("Enter the first number: ")) y = int(input("Enter the second number: ")) try: print("Result is %f" % (x / y)) except ZeroDivisionError: # 当 y 的值为 0 时,这里就能捕获到异常 print("The second number is zero")
除了“除数为0”这种程序自发的错误,我们还可以在某些不合法的情形下,使用 raise 语句人为地抛出异常。
raise 语句可以带一个参数,这个参数必须是一个(继承自 Exception 类的)类或者一个实例对象,如果参数是类的话,会自动创建一个该类的实例对象。
raise 语句也可以不带参数(通常用于 except 语句中,表明已经捕获到了某个异常对象),向上继续传递当前捕获到的异常对象(如果外围没有捕获该异常,则程序中断并报错)。
示例:
def foo(n): if n < 1: raise Exception # 人为抛出异常 while n > 0: x = int(input("Enter the first number: ")) y = int(input("Enter the second number: ")) try: print("Result is %f" % (x / y)) except ZeroDivisionError: # 捕获 除数为0 的异常 print("The second number is zero") raise # 继续传递 ZeroDivisionError 异常 n -= 1 try: foo(5) except: # 捕获任意异常 print("An exception was caught, stop running")
下图列举了一些常用的内置异常类:
注:上图截自《Python基础教程》第8章。
关于异常捕获:
示例:
def test(e): try: if (not e): pass else: raise e except ZeroDivisionError: # 捕获单个类型异常 print("Caught a ZeroDivisionError exception") except (TypeError, ValueError): # 捕获多个类型异常 print("Caught either a TypeError exception or a ValueError exception") except (IndexError, KeyError) as e: # 捕获异常对象 print("Caught an exception object", e) except: # 捕获任意异常 print("Caught an unknown exception") else: # 没有异常发生时才会执行 print("No exception") finally: # 只要上述 except 和 else 中不再发生异常,总是会执行到这里 print("finally") # 本示例中总是会会输出它 # 下面每一次 test() 调用后都会输出 finally,省略了未列出 test(ZeroDivisionError) # Caught a ZeroDivisionError exception test(TypeError) # Caught either a TypeError exception or a ValueError exception test(ValueError) # Caught either a TypeError exception or a ValueError exception test(IndexError) # (‘Caught an exception object‘, IndexError()) test(KeyError) # (‘Caught an exception object‘, KeyError()) test(Exception) # Caught an unknown exception test(None) # No exception
完。
原文:https://www.cnblogs.com/itwhite/p/12299739.html