NikoRan
NikoRan

Reputation: 41

How to I make exception in exception when catching errors in python?

So, I have this code, works very fine, but I want to have possibility if I input x it will return me to the beginning of choosing list I have

def ask2():
while True:
    try:
        number = int(input('Pick a number in range 1-100: '))
    except ValueError:  # just catch the exceptions you know!
        print('That\'s not a number!')
    else:
        if 1 <= number <= 100:  # this is faster
            print("added")
        else:
            print('Out of range. Try again')

Upvotes: 1

Views: 42

Answers (1)

Pedro Lobito
Pedro Lobito

Reputation: 98921

Guido van Rossum spent some time working with Java, which does support the equivalent of combining except blocks and a finally block, and this clarified what the statement should mean:

try:
    block-1 ...
except Exception1:
    handler-1 ...
except Exception2:
    handler-2 ...
else:
    else-block
finally:
    final-block

The code in block-1 is executed. If the code raises an exception, the various except blocks are tested: if the exception is of class Exception1, handler-1 is executed; otherwise if it's of class Exception2, handler-2 is executed, and so forth. If no exception is raised, the else-block is executed.

No matter what happened previously, the final-block is executed once the code block is complete and any raised exceptions handled. Even if there's an error in an exception handler or the else-block and a new exception is raised, the code in the final-block is still run.


PEP 341: Unifying try-except and try-finally

Upvotes: 1

Related Questions