Python - Exception Catching Exceptions

Introduction

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

Demo

def fetcher(obj, index): 
    return obj[index] 
             # from  ww  w.j a  v a 2  s  .c  o 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 ww  .java 2s  .co  m
    try: 
        x = 'asdf'
        fetcher(x, 4) 
    except IndexError: 
        print('got exception') 
    print('continuing') 

catcher()

Result