���� Python �̳� | ��13�� �쳣 | |
---|---|---|
��һҳ | try..finally | ��һҳ |
�������ڶ�һ���ļ���ʱ��ϣ���������쳣������������¶��ر��ļ�������ô���أ������ʹ��finally
������ɡ�ע�⣬��һ��try
���£������ͬʱʹ��except
�Ӿ��finally
�顣�����Ҫͬʱʹ�����ǵĻ�����Ҫ��һ��Ƕ������һ����
#!/usr/bin/python
# Filename: finally.py
import
time
try
:
f = file
(
'poem.txt'
)
while
True
:
# our usual file-reading idiom
line = f.readline()
if
len
(line) ==
0
:
break
time
.sleep(
2
)
print
line,
finally
:
f.close()
print
'Cleaning up...closed the file'
��Դ�ļ���code/finally.py��
$ python finally.py
Programming is fun
When the work is done
Cleaning up...closed the file
Traceback (most recent call last):
File "finally.py", line 12, in ?
time.sleep(2)
KeyboardInterrupt
���ǽ���ͨ���Ķ��ļ�������������������ÿ��ӡһ��֮ǰ��time.sleep
������ͣ2���ӡ���������ԭ�����ó������е���һЩ��Python�����䱾��ͨ�����еúܿ죩���ڳ������е�ʱ��Ctrl-c�ж�/ȡ������
���ǿ��Թ۲쵽KeyboardInterrupt
�쳣�������������˳��������ڳ����˳�֮ǰ��finally�Ӿ���Ȼ��ִ�У����ļ��ر�
��һҳ | ��һ�� | ��һҳ |
---|---|---|
�����쳣 | ��ҳ | ���� |