Python 简明教程

Python - Built-in Exceptions

内置异常是 Python 中预定义的错误类,用于处理程序中的错误和异常情况。它们派生自基类 “BaseException”,并且是标准库的一部分。

Standard Built-in Exceptions in Python

下面是 Python 中提供的标准异常列表:

以下是标准异常的一些示例 -

IndexError

在尝试访问无效索引的项目时显示。

numbers=[10,20,30,40]
for n in range(5):
   print (numbers[n])

它将生成以下 output

10
20
30
40
Traceback (most recent call last):

   print (numbers[n])
IndexError: list index out of range

ModuleNotFoundError

模块未找到时显示。

import notamodule
Traceback (most recent call last):

   import notamodule
ModuleNotFoundError: No module named 'notamodule'

KeyError

字典键未找到时出现。

D1={'1':"aa", '2':"bb", '3':"cc"}
print ( D1['4'])
Traceback (most recent call last):

   D1['4']
KeyError: '4'

ImportError

当指定的函数不可导入时显示。

from math import cube
Traceback (most recent call last):

   from math import cube
ImportError: cannot import name 'cube'

StopIteration

当迭代器流耗尽后调用 next() 函数时出现此错误。

.it=iter([1,2,3])
next(it)
next(it)
next(it)
next(it)
Traceback (most recent call last):

   next(it)
StopIteration

TypeError

当操作符或函数应用于不适当类型对象时显示。

print ('2'+2)
Traceback (most recent call last):

   '2'+2
TypeError: must be str, not int

ValueError

函数参数类型不当时显示。

print (int('xyz'))
Traceback (most recent call last):

   int('xyz')
ValueError: invalid literal for int() with base 10: 'xyz'

NameError

当找到对象时遇到此错误。

print (age)
Traceback (most recent call last):

   age
NameError: name 'age' is not defined

ZeroDivisionError

除数为零时显示。

x=100/0
Traceback (most recent call last):

   x=100/0
ZeroDivisionError: division by zero

KeyboardInterrupt

当用户在程序执行期间按正常中断键(通常为 Control-C)时。

name=input('enter your name')
enter your name^c
Traceback (most recent call last):

   name=input('enter your name')
KeyboardInterrupt

Hierarchy of Built-in Exceptions

Python 中的异常被组织在一个分级结构中,顶部是“BaseException”。下面是一个简化的层次结构 −

  1. BaseException SystemExitKeyboardInterrupt

  2. 异常 ArithmeticError FloatingPointErrorOverflowErrorZeroDivisionErrorAttributeErrorEOFErrorImportErrorLookupError IndexErrorKeyErrorMemoryErrorNameError UnboundLocalErrorOSError FileNotFoundErrorTypeErrorValueError --- (还有很多其他异常) ---

How to Use Built-in Exceptions

我们已经了解,Python 中的内置异常是预定义的类,专门处理特定错误条件。现在,这里有一个关于如何有效地在 Python 程序中使用它们的详细指南 −

Handling Exceptions with try-except Blocks

处理 Python 中的异常的主要方法是使用“try-except”块。这允许你捕获和响应在代码执行期间可能出现的异常。

Example

在下面的示例中,可能引发异常的代码放在“try”块中。“except”块捕获指定的异常“ZeroDivisionError”并处理它

try:
   result = 1 / 0
except ZeroDivisionError as e:
   print(f"Caught an exception: {e}")

以下是所获得的输出 −

Caught an exception: division by zero

Handling Multiple Exceptions

你可以通过在“except”块中指定元组的方式来处理多个异常,如以下示例所示 −

try:
   result = int('abc')
except (ValueError, TypeError) as e:
   print(f"Caught a ValueError or TypeError: {e}")

以上代码的输出如下所示 −

Caught a ValueError or TypeError: invalid literal for int() with base 10: 'abc'

Using "else" and "finally" Blocks

如果“try”子句中的代码块未引发异常,则执行“else”块 −

try:
   number = int(input("Enter a number: "))
except ValueError as e:
   print(f"Invalid input: {e}")
else:
   print(f"You entered: {number}")

上面代码的输出根据给定的输入而不同 −

Enter a number: bn
Invalid input: invalid literal for int() with base 10: 'bn'

无论是否发生了异常,“finally”块总是被执行。它通常用于清理操作,例如关闭文件或释放资源 −

try:
   file = open('example.txt', 'r')
   content = file.read()
except FileNotFoundError as e:
   print(f"File not found: {e}")
finally:
   file.close()
   print("File closed.")

以下是上面代码的输出: -

File closed.

Explicitly Raising Built-in Exceptions

在 Python 中,你可以引发内置异常以指示错误或代码中的特殊条件。这允许你处理特定的错误场景,并为调试应用程序的用户或开发人员提供信息性的错误消息。

Syntax

下面是引发内置异常的基本语法 −

raise ExceptionClassName("Error message")

Example

在这个示例中,“divide”函数尝试除以两个数字“a”和“b”。如果“b”为零,它将引发一条带有自定义消息的“ZeroDivisionError” −

def divide(a, b):
   if b == 0:
      raise ZeroDivisionError("Cannot divide by zero")
   return a / b

try:
   result = divide(10, 0)
except ZeroDivisionError as e:
   print(f"Error: {e}")

获得的输出如下所示 −

Error: Cannot divide by zero