Lazuardi N Putra
Lazuardi N Putra

Reputation: 428

Catching Error inside Else and Try

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.

Upvotes: 0

Views: 89

Answers (2)

user3522371
user3522371

Reputation:

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

Upvotes: 1

Burhan Khalid
Burhan Khalid

Reputation: 174758

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

Upvotes: 3

Related Questions