Python - Handling Errors with try Statements

Description

Handling Errors with try Statements

Demo

while True: 
    reply = input('Enter text:') 
    if reply == 'stop': break 
    try: # from w ww . ja  va 2s .c o m
        num = int(reply) 
    except: 
        print('Bad!' * 8) 
    else: 
        print(num ** 2) 
print('Bye')

Result

This try statement is another compound statement.

It's composed of the word try, followed by the main block of code, followed by an except part that gives the exception handler code.

And an else part to be run if no exception is raised in the try part.

Python first runs the try part, then runs either the except part (if an exception occurs) or the else part (if no exception occurs).

Related Topic