7 异常控制
2022.12.14 本学习内容总结于莫烦python:6.异常检查和处理
https://mofanpy.com/tutorials/python-basic/interactive-python/try-except
with open("no_file.txt", "r") as f:
print(f.read())
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
Input In [1], in <cell line: 1>()
----> 1 with open("no_file.txt", "r") as f:
2 print(f.read())
FileNotFoundError: [Errno 2] No such file or directory: 'no_file.txt'
报错没有这样的文件,报错关键字FileNotFoundError
7.1 try-except
try ①
except ②
:做①
,有条件再做②
try:
with open("no_file.txt", "r") as f:
print(f.read())
except FileNotFoundError as e:
print(e)
with open("no_file.txt", "w") as f:
f.write("I'm no_file.txt")
print("new file 'no_file.txt' has been written")
[Errno 2] No such file or directory: 'no_file.txt'
new file 'no_file.txt' has been written
用这种方式可以把报错内容输出:No such file or directory: 'no_file.txt'
,并进行相应的处理
- 多个异常
d = {"name": "f1", "age": 2}
l = [1,2,3]
try:
v = d["gender"]
l[3] = 4
except (KeyError, IndexError) as e:
print("key or index error for:", e)
key or index error for: 'gender'
如果你在原本的 `d` 中加上一个 `gender`, 让 `KeyError` 不报出来,它就会接着报字典的 `IndexError` 异常了。
也就是这里出现了两个错,报错只报第一个。能否
7.2 try-except-else
try①
except②
else③
:做①
,有条件做②
,没条件做③
- 【例1】
l = [1,2,3]
try:
l[3] = 4
except IndexError as e:
print(e)
else:
print("no error, now in else")
list assignment index out of range
错误确实是IndexError
,那么就执行②
不执行else
- 【例2】
l = [1,2,3,4]
try:
l[3] = 5
except IndexError as e:
print(e)
else:
print("no error, now in else")
no error, now in else
print(l)
[1, 2, 3, 5]
这里没有IndexError
错误,没有执行②
,执行了else
7.3 try-except-finally
这个finally
无论条件是否执行,它都会运行
-【例1】
l = [1,2,3]
try:
l[3] = 4
except IndexError as e:
print(e)
finally:
print("reach finally")
list assignment index out of range
reach finally
- 【例2】
l = [1,2,3,4]
try:
l[3] = 4
except IndexError as e:
print(e)
finally:
print("reach finally")
reach finally
- 【例3】
try:
dddd = dddddd
finally:
print("I know there is error, so what?")
I know there is error, so what?
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [7], in <cell line: 1>()
1 try:
----> 2 dddd = dddddd
3 finally:
4 print("I know there is error, so what?")
NameError: name 'dddddd' is not defined
他这个finally 你有异常吧,我不让你终止主程序,
7.4 raise手动触发异常
-
为了别人使用到我的代码时不至于骂街,或者异常后报出一大堆很难 debug 的信息。 这个时候我就该考虑考虑 raise 的用法了
-
你写了成百上千行代码,你也不能全记住代码的每一个细节。所以一旦报错,你也需要一个友善的错误信息提示,这时用 raise 准没错
def no_negative(num):
if num < 0:
raise ValueError("数字负了")
return num
print(no_negative(-1))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [9], in <cell line: 6>()
3 raise ValueError("数字负了")
4 return num
----> 6 print(no_negative(-1))
Input In [9], in no_negative(num)
1 def no_negative(num):
2 if num < 0:
----> 3 raise ValueError("数字负了")
4 return num
ValueError: 数字负了
就是自己来编辑 错误提示,来提醒。