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

实际开发中,捕获多个异常的方式
```pythoncoding=utf-8
try: print(‘——-test—1—-‘) open(‘123.txt’,’r’) # 如果123.txt文件不存在,那么会产生 IOError 异常 print(‘——-test—2—-‘) print(num)# 如果num变量没有定义,那么会产生 NameError 异常
except (IOError,NameError):
#如果想通过一次except捕获到多个异常可以用一个元组的方式print("捕捉到异常")
- 
<a name="aWcdC"></a>
## 捕捉所有异常

- 咱们应该对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 下执行"
