Python - Exception Catching Exceptions

Introduction

Wrap the call in a try statement to catch exceptions yourself:

Demo

def fetcher(obj, index): 
    return obj[index] 
             #   w  ww  . j av  a 2  s  .co m
try: 
     x = 'asdf'
     fetcher(x, 4) 
except IndexError:                      # Catch and recover 
     print('got exception')

Result

In a method

Demo

def fetcher(obj, index): 
    return obj[index] 
def catcher(): # from   w  w w .  j  ava  2 s .c  o m
    try: 
        x = 'asdf'
        fetcher(x, 4) 
    except IndexError: 
        print('got exception') 
    print('continuing') 

catcher()

Result