Python · 错误与异常

异常处理

  • try..except:一般来说我们会将所有可能引发异常或错误的语句放在 try 代码块中,将错误处理代码放置在 except 代码块中。
  • finally:总是会执行代码块,不论程序正常还是异常都会执行到。
  • raise:抛出异常,你能够引发的错误或异常必须是直接或间接从属于 Exception(异常) 类的派生类。
  • as:异常类别名。

示例exceptions_finally.py

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
30
31
import sys
import time

f = None
try:
f = open("poem.txt")
# 我们常用的文件阅读风格
while True:
line = f.readline()
if len(line) == 0:
break
print(line, end='')
sys.stdout.flush()
print("Press ctrl+c now")
# 为了确保它能运行一段时间
time.sleep(2)
except IOError:
print("Could not find file poem.txt")
except KeyboardInterrupt as ki:
print("!! You cancelled the reading from the file.")
finally:
if f:
f.close()
print("(Cleaning up: Closed the file)")

输出:
$ python exceptions_finally.py
Programming is fun
Press ctrl+c now
^C!! You cancelled the reading from the file.
(Cleaning up: Closed the file)