• 异常是指在语法正确的前提下,程序运行时报错就是异常。

image.png

  • image.png

    实际开发中,捕获多个异常的方式

    ```python

    coding=utf-8

    try: print(‘——-test—1—-‘) open(‘123.txt’,’r’) # 如果123.txt文件不存在,那么会产生 IOError 异常 print(‘——-test—2—-‘) print(num)# 如果num变量没有定义,那么会产生 NameError 异常

except (IOError,NameError):

  1. #如果想通过一次except捕获到多个异常可以用一个元组的方式
  2. print("捕捉到异常")

- ![image.png](https://cdn.nlark.com/yuque/0/2022/png/25502199/1641036569870-5cd6be2b-5e18-456e-9dab-7ed8768f16ba.png#clientId=u7683c057-8175-4&crop=0&crop=0&crop=1&crop=1&from=paste&id=ud0286e7d&margin=%5Bobject%20Object%5D&name=image.png&originHeight=221&originWidth=964&originalType=url&ratio=1&rotation=0&showTitle=false&size=93113&status=done&style=none&taskId=u0bc1ce39-4c94-44ee-b80f-c603ceea9ac&title=)
<a name="aWcdC"></a>
## 捕捉所有异常
![image.png](https://cdn.nlark.com/yuque/0/2022/png/25502199/1641036623778-6cf240b6-3ad9-4328-adca-0b9e13aca05a.png#clientId=u7683c057-8175-4&crop=0&crop=0&crop=1&crop=1&from=paste&id=ucf494ffb&margin=%5Bobject%20Object%5D&name=image.png&originHeight=229&originWidth=960&originalType=url&ratio=1&rotation=0&showTitle=false&size=116018&status=done&style=none&taskId=u3acff5b9-0f05-406d-aea8-905b32489b5&title=)

- 咱们应该对else并不陌生,在if中,它的作用是当条件不满足时执行的实行;同样在try…except…中也是如此,即如果没有捕获到异常,那么就执行else中的事情
```python
try:
    num = 100
    print(num)
except NameError as errorMsg:
    print('产生错误了:%s'%errorMsg)
else: # 没有异常才执行
    print('没有捕获到异常,真高兴')
import time
try:
    f = open('test.txt')
    try:
        while True:
            content = f.readline()
            if len(content) == 0:
                break
            time.sleep(2)
            print(content)
    except:
        #如果在读取文件的过程中,产生了异常,那么就会捕获到
        #比如 按下了 ctrl+c
        print("捕捉到异常")
    finally: # 无论有无异常都会执行
        f.close()
        print('关闭文件')
except:
    print("没有这个文件")

assert

断言
当表达式为True 才可执行

>>> assert True     # 条件为 true 正常执行
>>> assert False    # 条件为 false 触发异常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError
>>> assert 1==1    # 条件为 true 正常执行
>>> assert 1==2    # 条件为 false 触发异常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

>>> assert 1==2, '1 不等于 2'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: 1 不等于 2
实例
import sys
assert ('linux' in sys.platform), "该代码只能在 Linux 下执行"