Skip to content Skip to sidebar Skip to footer

Getting Exception Details In Python

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','w+') file

Solution 1:

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.

Solution 2:

Use the traceback module:

traceback.print_exc()

Solution 3:

You mention using a loop, but you're not actually using a loop. Use a loop. That way you can write each file, one at a time, inside a single try block. You don't appear to be doing anything with the files except write one value to each, so you don't need to keep them all open.

for filename in ['file1.txt', 'file2.txt', ...]:
    try:
        withopen(filename, 'w+') as f:
            f.write(str(a)+"whatever")
    except IOError:
        print("Error occurred with", filename)

Edit: If you have wildly different things to write to the different files, create a dictionary or other data structure ahead of time storing the mapping between files and data, then use that in the loop.

data = {'file1.txt': str(a), 'file2.txt': 'something else', 'file3.txt': str(a)+str(b)}

for filename, output in data.items():
    try:
        withopen(filename, 'w+') as f:
            f.write(output)
    except IOError:
        print("Error occurred with", filename)

Solution 4:

When using exc_type, value, exc_traceback = sys.exc_info(), note that the filename that generated the exception can be obtained through the following:

exc_traceback.tb_frame.f_locals.get('filename')

Post a Comment for "Getting Exception Details In Python"