Exception message (Python 2.6)

Viewed 83607

In Python, if I open a binary file that doesn't exist, the program exits with an error and prints:

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'

I can handle this with 'try-except', like:

try:
    pkl_file = open('monitor.dat', 'rb')
    monitoring_pickle = pickle.load(pkl_file)
    pkl_file.close()
except Exception:
    print 'No such file or directory'

How could I, in caught Exception, print the following line?

File "C:\Python_tests\Exception_Handling\src\exception_handling.py", 
line 11, in <module>
pkl_file = open('monitor.dat', 'rb')

So the program would not exit.

4 Answers
Related