当代码引用当前作用域中不存在的名称时,会引发 NameError 异常。例如,未限定的变量名。以下代码重写了如何捕获异常并找到其类型。示例 import sys try: def foo(): print magnolia foo() except NameError as e: print e print sys.exc_type 输出 C:/Users/TutorialsPoint1/~.py global name 'magnolia' is not defined
当序列引用超出范围时,会引发 IndexError 异常。以下代码重写了如何捕获异常并找到其类型。示例 import sys try: my_list = [3,7, 9, 4, 6] print my_list[6] except IndexError as e: print e print sys.exc_type 输出 C:/Users/TutorialsPoint1~.py list index out of range
ArithmeticError 异常是所有针对数值计算发生的错误的基类。它是以下内置异常的基类:OverflowError、ZeroDivisionError、FloatingPointError。我们可以如下捕获给定代码中的异常。示例 import sys try: 7/0 except ArithmeticError as e: print e print sys.exc_type print 'This is an example of catching ArithmeticError' 输出 integer division or modulo by zero This is an example of catching ArithmeticError