Exception message (Python 2.6)

Posted by TurboJupi on Stack Overflow See other posts from Stack Overflow or by TurboJupi
Published on 2009-11-11T13:35:37Z Indexed on 2010/05/09 20:48 UTC
Read the original article Hit count: 199

If I want to open binary file (in Python 2.6), that doesn't exists, program exits with an error and prints this:

    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'

Does anybody know, 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, program would not exits, and I would have useful information.

© Stack Overflow or respective owner

Related posts about python

Related posts about exception-handling