Explain Try, Except and Else statement in Python.

PythonServer Side ProgrammingProgramming

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
raja
Published on 06-Dec-2017 18:12:17
Advertisements