Menu
Coddy logo textTech

else

Lesson 4 of 16 in Coddy's Exception Handling in Python course.

  • We can use optional else block with try-except statement.
  • It is useful for code that must be executed if try block does not raise an Exception.

Example:

try:
   a = 10
   b = "hello"
   result = a + b  #code which can cause exception
except TypeError:
   print("Cannot do addition")  #code to handle exception
else:
   print("Addition performed successfully")  #code to be executed when no exception in try block

In above example, Exception is generated and control goes to except block. Here, else block will not be executed.

If you set b = 20, Exception will not occur and else block will be executed.

  • Exception --> except block
  • No Exception --> else block

Note:- Either of except or else part will be executed.

challenge icon

Challenge

Easy

We have a list 'data' containing 5 elements. Index position is an input to function fetch. Print element present at given index number. It will raise IndexError if index is out of range. print "Incorrect Index Number" on IndexError in except block. If no Exception, print fetched element in else block.

Try it yourself

data = ["John","United States",22,True,98.5]
def fetch(idx):
    #try block here (fetch)
    
    #except block here (Handle IndexError)
    
    #else block here (print fetched element)




All lessons in Exception Handling in Python