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())
Related
I am making a Reddit bot using PRAW and the code gives me the error that the exception is not iterable. Here is a simplification of my code:
try:
#something with praw that isn't relevant
except Exception as e: #this except error catches the APIexception, APIexpections in PRAW are a wide field of exceptions that dont't always have the same solution, so I scan the text for the error I'm looking for.
print(e)
if "keyword thats in the error" in e:
#fix the problem with the specific error
else:
print("Unkown APIExpection error")
This works fine for me, but when I run this code:
try:
#something
except Exception as e:
for character in e:
print(character)
#I also tried this
try:
#something
except Exception as e:
for character in str(e):
print(character)
#None of the above work but this is my actual code and what I need to do, anything that gets the above to work should work here too, I'm just letting you know this so that I don't get any other errors I have to ask another question for.
try:
#something
except Exception as e:
characterNum = 0
for character in e:
characterNum += 1
print(str(characterNum) + ": " + character)
It gives me a "TypeError: 'RedditAPIException' is not iterable", RedditAPIException can be ignore though as that's just the error I'm catching.
Convert the exception to string and then check in the if statement.
Change to => if "keyword thats in the error" in str(e):
In the code below when I ran it it suppose to catch all error with "except Exception as error:" return " Not possible" but thats
not the case when I set mystery_value = a it gives me a NameError. I don't understand this could someone help explain? Thanks.
mystery_value = a
try:
print(10/mystery_value)
except ZeroDivisionError as error:
print("Can't divide by zero")
except Exception as error:
print("Not possible")
it's because the error occurs before the try except block. it occurs at the first line because a doesn't refer to anything and it doesn't run reach the try except. if you replaced a with 'a' the exception would work.
mystery_value = 'a' # replace a with 'a'
try:
print(10/mystery_value)
except ZeroDivisionError as error:
print("Can't divide by zero")
except Exception as error:
print("Not possible")
output
Not possible
I have written Python code which does some calculation. During this it converts string to float. However sometimes numeric string value may be empty that time its giving me valueError. I tried to keep that in try catch block however its going to another exception block as shown below.
try:
float(some value)
except Exception as ValueError:
print(error message)
except Exception as oserror:
print(mesage)
Its going to os error block instead of ValueError block
That's not how you capture exceptions.
try:
float(some value)
except ValueError as e:
print("here's the message", e.args)
except OSError as e:
print("here's a different message")
(Note, though, there's no instance when calling float would raise an OSError.)
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.
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)