Traced Exceptions? [duplicate] - python

How can I get the full stack trace from the Exception object itself?
Consider the following code as reduced example of the problem:
last_exception = None
try:
raise Exception('foo failed')
except Exception as e:
last_exception = e
# this happens somewhere else, decoupled from the original raise
print_exception_stack_trace(last_exception)

Edit: I lied, sorry. e.__traceback__ is what you want.
try:
raise ValueError
except ValueError as e:
print( e.__traceback__ )
>c:/python31/pythonw -u "test.py"
<traceback object at 0x00C964B8>
>Exit code: 0
This is only valid in Python 3; you can't do it in earlier versions.

Related

How to get more information on exception error?

How can I get more information on the type of exception error ?
For example, in the code below I know the exception is gonna be ZeroDivisionError.
try:
print(1/0)
except ZeroDivisionError:
print("Error")
But I want to be able to get the information on the type of error without having to define it. I saw this example somewhere but it generates syntax error for me.
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain numbers\n", Argument
What I am mainly looking for is something like
try:
// Do something
except:
// Print out an information on the type of error
try:
# Do something
except Exception as e:
print(e)
You can replace Exception with ZeroDivisionError if you wish.
You can use stacktrace to get all the info about error.
https://docs.python.org/2/library/traceback.html
import stacktrace
try:
// Do something
except:
print(traceback.format_exc())

Python 2.7 exception handling syntax

I am bit confused about the try exception usage in Python 2.7.
try:
raise valueError("sample value error")
except Exception as e:
print str(e)
try:
raise valueError("sample value error")
except Exception,exception:
print str(exception)
try:
raise valueError("sample value error")
except exception:
print str(exception)
try:
raise valueError("sample value error")
except Exception:
print str(Exception) # it prints only the object reference
can some help me to understand the above usage?
Some concepts to help you understand the difference between the alternate variants of the except variants:
except Exception, e – This in an older variant, now deprecated, similar to except Exception as e
except Exception as e – Catch exceptions of the type Exception (or any subclass) and store them in the variable e for further processing, messaging or similar
except Exception – Catch exceptions of the type Exception (or any subclass), but ignore the value/information provided in the exception
except e – Gives me an compilation error, not sure if this related to python version, but if so, it should/would mean that you don't care about the type of exception but want to access the information in it
except – Catch any exception, and ignore the exception information
What to use, depends on many factors, but if you don't need the provided information in the exception there is no need to present the variable to catch this information.
Regarding which type of Exception to catch, take care to catch the accurate type of exceptions. If you are writing a general catch it all, it could be correct to use except Exception, but in the example case you've given I would opt for actually using except ValueError directly. This would allow for potentially other exceptions to be properly handled at another level of your code. The point is, don't catch exception you are not ready to handle.
If you want, you can read more on python 2.7 exception handling or available python 2.7 exception in the official documentation.
For Python 3 (also works in Python 2.7):
try:
raise ValueError("sample value error")
except Exception as e:
print(e)
For Python 2 (will not work in Python 3):
try:
raise ValueError("sample value error")
except Exception, e:
print e
I use:
try:
raise valueError("sample value error")
except Exception as e:
print str(e)
When I want to declare a specific error and
try:
raise valueError("sample value error")
except:
print "Something unexpected happened"
When I don't really care or except: pass , except: return etc
Use the format
try:
raise ValueError("sample value error")
except Exception, e:
print e

Python trying fails

I am trying in Python.
try:
newbutton['roundcornerradius'] = buttondata['roundcornerradius']
buttons.append(newbutton)
buttons is a list. roundcornerradius is optional in buttondata.
Alas this gives
buttons.append(newbutton)
^ SyntaxError: invalid syntax
I just want to ignore the cases where roundcornerradius does not exist. I don't need any error reported.
why arent you using the except keyword
try:
newbutton['roundcornerradius'] = buttondata['roundcornerradius']
buttons.append(newbutton)
except:
pass
this will try the first part and if an error is thrown it will do the except part
you can also add the disered error you want to except a certain error like this
except AttributeError:
you can also get the excepted error by doing this:
except Exception,e: print str(e)
You should catch a try with exception:
try:
code may through exception
except (DesiredException):
in case of exception
Also you can use else with try if you need to populate new buttons only when try succeeds:
try:
newbutton['roundcornerradius'] = buttondata['roundcornerradius']
except KeyError:
pass
else:
buttons.append(newbutton)
single except: with no exception class defined will catch every exception raised which may not be desired in some cases.
Most probably you will get KeyError on your code but I am not sure.
See here for builtin exceptions:
http://docs.python.org/2/library/exceptions.html
You must close block with except or finally if using try.
try:
newbutton['roundcornerradius'] = buttondata['roundcornerradius']
except KeyError:
pass#omit raise if key 'roundcornerradius' does not exists
buttons.append(newbutton)
If you know default value for 'roundcornerradius' - you dont need no try ... except
newbutton['roundcornerradius'] = buttondata.get('roundcornerradius', DEFAULT_RADIUS)
buttons.append(newbutton)

python3 re-raising an exception with custom attribute?

here's my code from python2 which needs to be 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, I can get the whole exception with the problematic input file by checking whether an exception has 'filename' attribute.
however python3's raise has been changed. this is what 2to3 gave me for above code:
except Exception as e:
et, ei, tb = sys.exc_info()
e.filename = filename
raise et(e).with_traceback(tb)
which gives me another error and I don't think filename attribute is preserved:
in __call__
raise et(e).with_traceback(tb)
TypeError: function takes exactly 5 arguments (1 given)
What I just want is passing exceptions transparently with some information to track the input file. I miss python2's raise [exception_type[,exception_instance[,traceback]]] - How can I do this in python3?
You can set the __traceback__ attribute:
except Exception as e:
et, ei, tb = sys.exc_info()
ei.filename = filename
ei.__traceback__ = tb
raise ei
or call .with_traceback() directly on the old instance:
except Exception as e:
et, ei, tb = sys.exc_info()
ei.filename = filename
raise ei.with_traceback(tb)
However, the traceback is already automatically attached, there is no need to re-attach it, really.
See the raise statement documentation:
A traceback object is normally created automatically when an exception is raised and attached to it as the __traceback__ attribute, which is writable.
In this specific case, perhaps you wanted a different exception instead, with context?
class FilenameException(Exception):
filename = None
def __init__(self, filename):
super().__init__(filename)
self.filename = filename
try:
something(filename)
except Exception as e:
raise FilenameException(filename) from e
This would create a chained exception, where both exceptions would be printed if uncaught, and the original exception is available as newexception.__context__.
You don't need to do anything; in Python 3 re-raised exceptions automatically have a full traceback from where they were originally raised.
try:
do_something_with_file(filename)
except Exception as exc_inst:
exc_inst.filename = filename
raise exc_inst
This works because PyErr_NormalizeException sets the __traceback__ attribute appropriately on catching an exception in an except statement; see http://www.python.org/dev/peps/pep-3134/.

Error in Exception handling in Python script

m = ldap.initialize(server)
try:
m.start_tls_s()
except ldap.LDAPError, e:
print e
This part of a python script. I am getting the error in the line "except ldap.LDAPError, e:". But it seems to be right. Can anyone help?
Thanks!
If you use Python 3 that's
m = ldap.initialize(server)
try:
m.start_tls_s()
except ldap.LDAPError as e:
print(e)
See the language reference.

Categories