Handling Errors with try Statements
while True: reply = input('Enter text:') if reply == 'stop': break try: # ww w.j ava2s. c o m num = int(reply) except: print('Bad!' * 8) else: print(num ** 2) print('Bye')
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).