Exception in python unknown errors - python

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

Related

Given error when trying to iterate through an exception

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

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

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

Pass Exception to next except statement

I'm catching exceptions with a try...except block in Python. The program tries to create a directory tree using os.makedirs. If it raises WindowsError: directory already exists, I want to catch the exception and just do nothing. If any other exception is thrown, I catch it and set a custom error variable and then continue with the script.
What would theoretically work is the following:
try:
os.makedirs(path)
except WindowsError: print "Folder already exists, moving on."
except Exception as e:
print e
error = 1
Now I want to enhance this a bit and make sure that the except block for WindowsError only treats those exceptions where the error message contains "directory already exists" and nothing else. If there is some other WindowsError I want to treat it in the next except statement. But unfortunately, the following code does not work and the Exception does not get caught:
try:
os.makedirs(path)
except WindowsError as e:
if "directory already exists" in e:
print "Folder already exists, moving on."
else: raise
except Exception as e:
print e
error = 1
How can I achieve that my first except statement specifically catches the "directory already exists" exception and all others get treated in the second except statement?
Use one exception block and special case your handling there; you can just use isinstance() to detect a specific exception type:
try:
os.makedirs(path)
except Exception as e:
if isinstance(e, WindowsError) and "directory already exists" in e:
print "Folder already exists, moving on."
else:
print e
error = 1
Note that I'd not rely on the container-like nature of exceptions here; I'd test the args attribute explicitly:
if isinstance(e, WindowsError) and e.args[0] == "directory already exists":

Categories