How to catch error inside "else" which that "else" inside "try". Here is the code:
try:
if appcodex == app:
print "AppCode Confirmed"
if acccodex == acc:
print "Access Code Confirmed"
if cmdcodex == cmd:
print "Command Code Confirmed"
print "All Code Confirmed, Accessing URL..."
else:
print "Command Code not found"
else:
print "Access Code not found"
else:
print "AppCode not found"
except:
print "Error : Code doesn't match..."
How to raise "CommandCode not found" instead of "Error : Code doesn't match..." when cmdcodex/cmd has no input.
2 Answers 2
You'll need to create your own exception and raise it. Its as simple as creating a class that inherits from Exception, then using raise:
>>> class CommandCode(Exception):
... pass
...
>>> raise CommandCode('Not found')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.CommandCode: Not found
Comments
It is normal you get "Error : Code doesn't match..." instead of "Command Code not found". Why ? The answer is basic: you need to understand the basic concepts of handling exceptions in Python.
In your special case, you must wrap that piece of code within a try .. except block also, like this:
try:
if appcodex == app:
print "AppCode Confirmed"
if acccodex == acc:
print "Access Code Confirmed"
try:
if cmdcodex == cmd:
print "Command Code Confirmed"
print "All Code Confirmed, Accessing URL..."
except:
print "Command Code not found"
else:
print "Access Code not found"
else:
print "AppCode not found"
except:
print "Error : Code doesn't match..."
To sum up the situation: you can nest as necessary try ... except blocks as you need. But you should follow this PEP
tryand certainly avoid bareexcept(see e.g. this). What is it that you are trying to do?None, or"", or unassigned? What error are you guarding against?try.