python - python3 re-raising an exception with custom attribute? -
here's code python2 needs ported:
try: do_something_with_file(filename) except: exc_type, exc_inst, tb = sys.exc_info() exc_inst.filename = filename raise exc_type, exc_inst, tb
with above code, can whole exception problematic input file checking whether exception has 'filename' attribute.
however python3's raise has been changed. 2to3 gave me above code:
except exception e: et, ei, tb = sys.exc_info() e.filename = filename raise et(e).with_traceback(tb)
which gives me error , don't think filename attribute preserved:
in __call__ raise et(e).with_traceback(tb) typeerror: function takes 5 arguments (1 given)
what want passing exceptions transparently information track input file. miss python2's raise [exception_type[,exception_instance[,traceback]]]
- how can in python3?
you can set __traceback__
attribute:
except exception e: et, ei, tb = sys.exc_info() ei.filename = filename ei.__traceback__ = tb raise ei
or call .with_traceback()
directly on old instance:
except exception e: et, ei, tb = sys.exc_info() ei.filename = filename raise ei.with_traceback(tb)
however, traceback automatically attached, there no need re-attach it, really.
see raise
statement documentation:
a traceback object created automatically when exception raised , attached
__traceback__
attribute, writable.
in specific case, perhaps wanted different exception instead, context?
class filenameexception(exception): filename = none def __init__(self, filename): super().__init__(filename) self.filename = filename try: something(filename) except exception e: raise filenameexception(filename) e
this create chained exception, both exceptions printed if uncaught, , original exception available newexception.__context__
.
Comments
Post a Comment