> For the complete documentation index, see [llms.txt](https://johannesliu.gitbook.io/data-science-python-implemented/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://johannesliu.gitbook.io/data-science-python-implemented/4.0-practice/4.5-exception.md).

# 4.5 异常处理

我们在运行代码时，经常会遇到这两种提示，“异常”和“错误”。在我们深入学习异常处理之前，我们有必要对“错误”进行讲解。

程序的**错误**可以分为三类：**语法错误**、**运行错误**和**逻辑错误**。

语法错误：是由于在编程过程中，键入的代码中包含了不符合编译器语法规则的内容所导致的错误。例如python中最常见到的缩进错误，数据类型匹配错误等。在IDE或编辑器中，配置” intelisense”功能后，可以对这些错误进行诊断和提示，甚至可以自动代替编写者对问题代码进行纠正。

运行错误：是指程序在运行过程中出现的错误。例如，进行数值计算时出现的除零错误，元组下标越界、找不到目标文件等。

逻辑错误：程序在运行后，没有得到代码编写者预期的结果，这一类错误称为逻辑错误。例如：赋值错误，条件错误，算法设计错误等。

**异常**是指程序在执行过程中出错时，在正常控制流以外执行的命令。python解释器逐行对代码进行解释的过程中，每检测到一个错误，解释器就会抛出一个异常（停止运行指令，并给用户提示）。除了由Python定义的异常以外，还有用户自定义的异常。

a常见的Python标准异常类如表2.x所示：

| 异常类名              | 描述               |
| ----------------- | ---------------- |
| Exception         | 所有异常类的父类         |
| NameError         | 尝试访问一个没有声明的变量    |
| SyntaxError       | 语法错误             |
| ZeroDivisionError | 除零错误             |
| IOError           | 输入/输出操作失败        |
| KeyboardInterrupt | 用户中断执行(键入ctrl+c) |
| EOFError          | 输入结束或文件不符合期望     |
| ValueError        | 函数传参错误           |
| AttributeError    | 尝试访问位置的对象属性      |

### 4.4.1 try/except

try…except是最常见的异常处理语句。它用于捕捉try子句中的异常，并通过except子句，对try子句中出现的异常进行处理。try语句通常有两种形式：一种不含有else分支，称为单分支结构，另外一种则含有一个或多个else分支，称为多分支结构。这点与if语句是相似的。

单分支结构语句格式如下：

try:

statement1 #被检测的语句

except Except\[, reason]

actions #若发生Except1异常，就执行操作action1

else:

statement2

多分支结构语句格式如下：

try:

statement1 #被检测语句

except Except1\[, reason]:

action1 #若发生Except1异常，就执行操作action1

except Except2\[, reason]:

action2 #若发生Except2异常，就执行操作action2

\[…] #若干except块

else:

statement2

### 4.4.2 try/finally

finally子句是一段无论异常是否发生或者发生后是否被捕获都会被执行的代码。

单分支结构语句格式如下：

try:

statement1 #被检测的语句

finally:

statement2

多分支结构语法格式如下：

try:

statement1

except Except1\[, reason]:

action1 #若发生Except1异常，就执行操作action1

except Except2\[, reason]:

action2 #若发生Except2异常，就执行操作action2

\[except…] #若干except块

\[else] #else块

finally:

statement2

### 4.4.3 raise

之前我们介绍的异常，都是由python解释器出发的。如果我们需要在自己的程序中主动触发异常，就可以使用rasie语句。我们通过raise语句指明错误或异常名称。

rase语句的语法格式如下：

raise\[Exception\[, args,\[, traceback]]

其中，Exception是异常类，或异常类的**实例**。args是传递给Exception的参数。traceback用来提供1个跟踪记录对象。

例：

\>>>raise AttributeError

Traceback (most recent call last):

File "\<pyshell#32>", line 1, in \<module>

raise AttributeError

AttributeError

\>>> raise AttributeError (“出现了属性错误”)

### 4.4.4 assert

在编写代码的过程中，我们有时候会剔除一些假设，assert（断言）就是用于在代码中捕捉这些假设，来验证其正确与否。断言表示为一些布尔表达式。当假设（布尔表达式）正确时，assert语句就什么都不做。如果假设错误时，就会抛出异常。

assert语句的语法格式如下：

\>>>assert 1==1

\>>>assert 1>2

Traceback (most recent call last):

File "\<pyshell#31>", line 1, in \<module>

assert 1>3

AssertionError

因为布尔表达式1>2为假，因此抛出AssertionError异常，传入的字符串成为异常类的实例的具体信息。

### 4.4.6 sys模块回溯异常

使用sys模块下的exc\_info函数，我们可以获取程序最后出现的异常。exc\_info函数返回一个三元组（type， value，traceback）。其中type是异常的类型，value是异常的参数，traceback是包含调用栈信息的对象。

代码清单

\#divide\_0.py

import sys

try:

1/0

except:

exc\_info=sys.exc\_info()

exc\_info

输出结果

(ZeroDivisionError,

ZeroDivisionError('division by zero'),

\<traceback at 0x202e5a0ac88>)

从输出中，我们可以知道，程序发生了除零错误。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://johannesliu.gitbook.io/data-science-python-implemented/4.0-practice/4.5-exception.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
