Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Explain Try, Except and Else statement in Python.

I have the following code that throws an exception as follows

a = [11, 8, 9, 2]
try:
    foo = a[5]
except:
    print "index out of range"

showing output as

index out of range

How do I rewrite this code to use the else clause?


1 Answer
Rajendra Dharmkar

The common method to handle exceptions in python is using the "try-except" block. We can even include an else clause after except clause. The statements in the else block are executed if there is no exception in the try statement.

The optional else clause is executed if and when control flows off the end of the try clause except in the case of an exception or the execution of a return, continue, or break statement.

The given code can be rewritten as follows

a = [11, 8, 9, 2]
try:
foo = a[3]
except:
print "index out of range"
else:
print "index well within range"

This gives the output

index well within range
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.