Exception message (Python 2.6)

后端 未结 4 1251
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 10:02

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_te         


        
相关标签:
4条回答
  • 2020-12-05 10:15

    This prints the exception message:

    except Exception, e:
        print "Couldn't do it: %s" % e
    

    This will show the whole traceback:

    import traceback
    
    # ...
    
    except Exception, e:
        traceback.print_exc()
    

    But you might not want to catch Exception. The narrower you can make your catch, the better, generally. So you might want to try:

    except IOError, e:
    

    instead. Also on the subject of narrowing your exception handling, if you are only concerned about missing files, then put the try-except only around the open:

    try:
        pkl_file = open('monitor.dat', 'rb')
    except IOError, e:
        print 'No such file or directory: %s' % e
    
    monitoring_pickle = pickle.load(pkl_file)
    pkl_file.close()
    
    0 讨论(0)
  • 2020-12-05 10:21

    If you want to capture the exception object passed by the Exception, it's best to start using the NEW format introduced in Python 2.6 (which currently supports both) because it will be the only way to do it into Python 3.

    And that is:

    try:
        ...
    except IOError as e:
        ...
    

    Example:

    try:
        pkfile = open('monitor.dat', 'rb')
    except IOError as e:
        print 'Exception error is: %s' % e
    

    A detailed overview can be found at the What's New in Python 2.6 documentation.

    0 讨论(0)
  • 2020-12-05 10:25

    Thanks for all.

    That's, what I needed :)

    import traceback
    
    try:
        # boom
    except Exception:
        print traceback.format_exc()
    
    0 讨论(0)
  • 2020-12-05 10:33

    Python has the traceback module.

    import traceback
    try:
        pkl_file = open('monitor.dat', 'rb')
        monitoring_pickle = pickle.load(pkl_file)
        pkl_file.close()
    except IOError:
        traceback.print_exc()
    
    0 讨论(0)
提交回复
热议问题