Explain Try, Except and Else statement in Python.


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.

Example

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"

Output

This gives the output

index well within range

Updated on: 12-Feb-2020

878 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements