Getting exception details in Python

前端 未结 4 819
故里飘歌
故里飘歌 2021-02-04 00:04

I have to open & write to about 10 different files all within the same loop. e.g:

for i in range(0,10):
    try:
        a=5
        file1 = open(\"file1.txt         


        
4条回答
  •  无人及你
    2021-02-04 00:43

    You can use sys.exc_info to get information about the exception currently being handled, including the exception object itself. An IOError exception contains all of the information you need, including the filename, the errno, and a string describing the error:

    import sys
    
    try:
        f1 = open('example1')
        f2 = open('example2')
    except IOError:
        type, value, traceback = sys.exc_info()
        print('Error opening %s: %s' % (value.filename, value.strerror))
    

    Execution in the try block will obviously still halt after the first exception.

提交回复
热议问题