在Python,如果我打開一個不存在的二進制文件,程序有錯誤,並打印退出:異常消息(Python 2.6中)
Traceback (most recent call last):
File "C:\Python_tests\Exception_Handling\src\exception_handling.py",
line 4, in <module>
pkl_file = open('monitor.dat', 'rb')
IOError: [Errno 2] No such file or directory: 'monitor.dat'
我可以處理這個「嘗試 - 除了」 ,如:
try:
pkl_file = open('monitor.dat', 'rb')
monitoring_pickle = pickle.load(pkl_file)
pkl_file.close()
except Exception:
print 'No such file or directory'
我怎麼能在抓到Exception時打印下面這行?
File "C:\Python_tests\Exception_Handling\src\exception_handling.py",
line 11, in <module>
pkl_file = open('monitor.dat', 'rb')
所以程序不會退出。
這不適合我。喬亨的回答的確如此。 – Josh
@Josh這個答案和這個答案非常相似。 –