Cv Nikhil
Cv Nikhil

Reputation: 23

why is it not catching index errror?

def dict_items(dict1):
    try:
        d2={}
        for k in dict1.keys():
            d2[k+1]=dict1[k]+k
            dict1[k]=d2[k]       
    except IndexError:
        print("IndexError")
    except ValueError:
        print("ValueError")
    finally:
        print("Finally done")

try:
    dict_items({1:1,2:22,3:33})
    print("function call done")
except:
    print("Exception")
finally:
    print("inside finally")

The above executes correctly and prints

Finally done
Exception
inside finally

why is not catching index error is there anything I am missing?

Upvotes: 0

Views: 40

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177800

A bare except: isn't very useful. Catch the exception as print its type to see your error:

def dict_items(dict1):
    try:
        d2={}
        for k in dict1.keys():
            d2[k+1]=dict1[k]+k
            dict1[k]=d2[k]       
    except IndexError:
        print("IndexError")
    except ValueError:
        print("ValueError")
    finally:
        print("Finally done")

try:
    dict_items({1:1,2:22,3:33})
    print("function call done")
except Exception as e:
    print("Exception",type(e))
finally:
    print("inside finally")

Output:

Finally done
Exception <class 'KeyError'>
inside finally

Dictionaries throw KeyError not IndexError when the key doesn't exist, so the dict_items try block catches nothing and prints Finally done, then the outer try catches the KeyError in the bare except. Exception is the base class of most exceptions so you can see what type and value it has, then the final finally prints inside finally.

Upvotes: 2

Related Questions