I have some code where I parse a file. It’s simple, like so:
for line in config_file:
line_split=line.split("|")
pid_index = int(line_split[3])
date_locations = [int(i) for i in line_split[2].split(",")]
in_file = line_split[0]
out_file = line_split[1]
file_info.append([in_file, out_file, date_locations, pid_index])
If something occurs I want Python to proceed printing its usual error messages, but I want to add an additional line at the end of the regular error message, something like:
except:
print "line \"{0}\" might have failed to parse".format(line.rstrip())
However, with the code above only the extra info line is shown – the regular error messages are overwritten!
I have tried adding the following to my catch, but it produces ugly output:
e = sys.exc_info()
for i in e:
print i
Is there a simple way to have Python print the regular error messages plus an additional line of info of my choosing?
I think the best option here (and I removed my other solution in this edit, as I feel it’s actually not a great one) is to create your own exception that describes your problem, and then use it atop the exception you have:
then:
Which will produce something like:
(I used a
NameErrorasSomeErrorfor the example)Note that I have added a specific exception to your
exceptline – this is always worth doing, as catching any exception could cause you to ignore errors you don’t mean to.This method has the advantage of making your code easier to use by other software, as they can catch this particular exception.
The
fromsyntax on an exception tells Python the root cause of the exception. Otherwise, Python will assume the new exception was an error occurring during the handling of the exception. Note this is only available in Python 3.x, in earlier versions, you will have to do this manually. I would suggest usingtraceback.format_exc()then printing that as part of your exception’s error message.