0%

Mosh的Python课程笔记(6)--Exceptions

Mosh的课程网址

Handling Exceptions

1
2
3
4
5
6
7
8
9
10
try:
age = int(input("Age: "))
except ValueError as ex:
print("You didn't enter a valid age.")
print(ex) # 输出错误信息
print(type(ex)) # 显示错误类型
else: # 没有exception就执行这一块
print("No exceptions were thrown.")

print("Execution continues.")

运行结果:

1
2
3
4
5
6
7
8
9
10
11
>python app.py
Age: 10
No exceptions were thrown.
Execution continues.

>python app.py
Age: a
You didn't enter a valid age.
invalid literal for int() with base 10: 'a'
<class 'ValueError'>
Execution continues.

Handling Different Exceptions

1
2
3
4
5
6
7
try:
age = int(input("Age: "))
xfactor = 10 / age
except (ValueError, ZeroDivisionError): # 多种exception之一即执行
print("You didn't enter a valid age.")
else:
print("No exceptions were thrown.")

输出结果:

1
2
3
> python app.py
Age: 0
You didn't enter a valid age.

Cleaning Up

1
2
3
4
5
6
7
8
9
10
try:
file = open("app.py")
age = int(input("Age: "))
xfactor = 10 / age
except (ValueError, ZeroDivisionError):
print("You didn't enter a valid age.")
else:
print("No exceptions were thrown.")
finally:
file.close()

无论有没有出现exception,都要释放资源,那就放在finally块里,无论有没有exception都会执行的。

The With Statement

使用with语句打开文件,随后会自动释放掉,就不用file.close()了:

1
2
with open("app.py") as file:
print("File opened.")

file有__enter__和__exit__两个magic function,最后会自动调用__exit__,所以不用手动释放。

Raising Exceptions

1
2
3
4
5
6
7
8
9
10
def calculate_xfactor(age):
if age <= 0:
raise ValueError("Age cannot be 0 or less.")
return 10 / age


try:
calculate_xfactor(-1)
except ValueError as error:
print(error)

Cost of Raising Exceptions

Mosh 不建议raise exceptions,因为代价有点大。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from timeit import timeit

code1 = """
def calculate_xfactor(age):
if age <= 0:
raise ValueError("Age cannot be 0 or less.")
return 10 / age


try:
calculate_xfactor(-1)
except ValueError as error:
pass
"""

code2 = """
def calculate_xfactor(age):
if age <= 0:
return None
return 10 / age


xfactor = calculate_xfactor(-1)
if xfactor == None:
pass
"""

print("first code=", timeit(code1, number=10000))
print("second code=", timeit(code2, number=10000))

输出结果:

1
2
first code= 0.0040202000000000016
second code= 0.0015166999999999958

可以看到raise exception的用时是普通方法的两倍多。