Python异常

什么是异常?

异常即是一个事件,该事件会在程序执行过程中发生,影响了程序的正常执行。
一般情况下,在Python无法正常处理程序时就会发生一个异常。
异常是Python对象,表示一个错误。
当Python脚本发生异常时我们需要捕获处理它,否则程序会终止执行。

常见异常类型

异常名称 描述
FileNotFoundError 找不到指定文件的异常
NameError 未声明/初始化对象 (没有属性)
BaseException 所有异常的基类

异常处理语句

  • try…except…
  • try..except…finally
  • try…except…finally
  • raise

try….except

FileNotFoundError

1
2
3
4
5
try:         
fileName=input("Please input fileName:")
open("%r.txt" %fileName)
except FileNotFoundError:
print("%r文件未找到" %fileName)

NameError

1
2
3
4
try:
print(stu)
except NameError:
print("变量未定义")

BaseException

1
2
3
4
try:
print(stu)
except BaseException:
print("变量未定义")

定位异常的行

1
2
3
4
5
6
7
try:
stu='Jack'
print(stu)
print(stu2)
print(stu3)
except BaseException as msg:
print(msg)

try… except… else 使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
try:
stu='Jack'
print(stu)
except BaseException as msg:
print(msg)
else:
print("stu is defined!")
```

#### try..except...finally 输出
```python
try:
#stu='Jack'
print(stu)
except BaseException as msg:
print(msg)
finally:
print("The end !")

raise 抛出异常

1
2
3
4
5
6
7
8
9
def division(x,y):
if y==0:
raise ZeroDivisionError("Zero is not allow!")
return x/y

try:
division(8,0)
except BaseException as msg:
print(msg)