Given error when trying to iterate through an exception - python

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):

Related

python catching "all other error" type example case

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

Handling exception in Python

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 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())

Exception in python unknown errors

except ValueError:
print "the input is Invaild(dd.mm.year)"
except as e:
print "Unknown error"
print e
This is the code I wrote, if an error different then valueerror will happen will it print it in e?
thanks
You'll need to catch the BaseException or object here to be able to assign to e:
except ValueError:
print "the input is Invaild(dd.mm.year)"
except BaseException as e:
print "Unknown error"
print e
or, better still, Exception:
except ValueError:
print "the input is Invaild(dd.mm.year)"
except Exception as e:
print "Unknown error"
print e
The blanket except: will catch the same exceptions as BaseException, catching just Exception will ignore KeyboardInterrupt, SystemExit, and GeneratorExit. Not catching these there is generally a good idea.
For details, see the exceptions documentation.
No, that code will throw a SyntaxError:
If you don't know the exception your code might throw, you can capture for just Exception. Doing so will get all built-in, non-system-exiting exceptions:
except ValueError:
print "the input is Invaild(dd.mm.year)"
except Exception as e:
print "Unknown error"
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)

Categories