Contents

Try Except Versus if Else

Contents

Lets say we want to access the first fruit but we don’t know if the list has any fruits in it.

You would ask: Are there any fruits?

1
2
3
4
if fruits:
    favourite = fruit[0]
else:
    favourite = 'orange'

Why not take what you want straight forward..

1
2
3
4
try:
    im_taking_it = fruits[0]
except IndexError:
    oops_forgive_me = 'orange'

..and if it is not there forgive yourself :)

EAFP: Easier to ask for forgiveness than permission