Python 简明教程

Python - Built-in Exceptions

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

Built-in exceptions are pre-defined error classes in Python that handle errors and exceptional conditions in programs. They are derived from the base class "BaseException" and are part of the standard library.

Standard Built-in Exceptions in Python

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

Here is a list of Standard Exceptions available in Python −

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

Here are some examples of standard exceptions −

IndexError

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

It is shown when trying to access item at invalid index.

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

它将生成以下 output

It will produce the following output

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

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

ModuleNotFoundError

模块未找到时显示。

This is displayed when module could not be found.

import notamodule
Traceback (most recent call last):

   import notamodule
ModuleNotFoundError: No module named 'notamodule'

KeyError

字典键未找到时出现。

It occurs as dictionary key is not found.

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

   D1['4']
KeyError: '4'

ImportError

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

It is shown when specified function is not available for import.

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

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

StopIteration

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

This error appears when next() function is called after iterator stream exhausts.

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

   next(it)
StopIteration

TypeError

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

This is shown when operator or function is applied to an object of inappropriate type.

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

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

ValueError

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

It is displayed when function’s argument is of inappropriate type.

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

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

NameError

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

This is encountered when object could not be found.

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

   age
NameError: name 'age' is not defined

ZeroDivisionError

除数为零时显示。

It is shown when second operator in division is zero.

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

   x=100/0
ZeroDivisionError: division by zero

KeyboardInterrupt

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

When user hits the interrupt key normally Control-C during execution of program.

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”。下面是一个简化的层次结构 −

The exceptions in Python are organized in a hierarchical structure, with "BaseException" at the top. Here is a simplified hierarchy −

  1. BaseException SystemExitKeyboardInterrupt

  2. Exception ArithmeticError FloatingPointErrorOverflowErrorZeroDivisionErrorAttributeErrorEOFErrorImportErrorLookupError IndexErrorKeyErrorMemoryErrorNameError UnboundLocalErrorOSError FileNotFoundErrorTypeErrorValueError---(Many others)---

How to Use Built-in Exceptions

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

As we already know that built-in exceptions in Python are pre-defined classes that handle specific error conditions. Now, here is a detailed guide on how to use them effectively in your Python programs −

Handling Exceptions with try-except Blocks

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

The primary way to handle exceptions in Python is using "try-except" blocks. This allows you to catch and respond to exceptions that may occur during the execution of your code.

Example

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

In the following example, the code that may raise an exception is placed inside the "try" block. The "except" block catches the specified exception "ZeroDivisionError" and handles it

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

以下是所获得的输出 −

Following is the output obtained −

Caught an exception: division by zero

Handling Multiple Exceptions

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

You can handle multiple exceptions by specifying them in a tuple within the "except" block as shown in the example below −

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

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

Output of the above code is as shown below −

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

Using "else" and "finally" Blocks

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

The "else" block is executed if the code block in the "try" clause does not raise an exception −

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

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

Output of the above code varies as per the input given −

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

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

The "finally" block is always executed, regardless of whether an exception occurred or not. It’s typically used for clean-up actions, such as closing files or releasing resources −

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.")

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

Following is the output of the above code −

File closed.

Explicitly Raising Built-in Exceptions

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

In Python, you can raise built-in exceptions to indicate errors or exceptional conditions in your code. This allows you to handle specific error scenarios and provide informative error messages to users or developers debugging your application.

Syntax

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

Following is the basic syntax for raising built-in exception −

raise ExceptionClassName("Error message")

Example

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

In this example, the "divide" function attempts to divide two numbers "a" and "b". If "b" is zero, it raises a "ZeroDivisionError" with a custom message −

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}")

获得的输出如下所示 −

The output obtained is as shown below −

Error: Cannot divide by zero