In [1]:
# exceptions are used to indicate that an error has occurred
# that prevents proceeding further

# Python defines exceptions for a number of typical cases.
# When those cases, the exception is "raised"

# For example:

23 / 0


---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-1-d4f1fd7bd966> in <module>()
      7 # For example:
      8 
----> 9 23 / 0

ZeroDivisionError: integer division or modulo by zero

In [2]:
big_numbers = {
    'big': 100,
    'huge': 1000000,
    'vast': 1000000000000
}

big_numbers['enormous']


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-2-bb0c19ec605c> in <module>()
      5 }
      6 
----> 7 big_numbers['enormous']

KeyError: 'enormous'

In [ ]:
# "ZeroDivisionError" and "KeyError" are classes of exceptions.

In [3]:
# Sometimes you want to proceed even after an exception has been raised.
# In this case you can protect a block of code from halting on an exception
# using this syntax

try:
    print 'Doing something'
except:
    print 'There was a problem'


Doing something

In [5]:
try:
    value = 23 / 0
    print 'We did it!!!!'
except:
    print 'Warning: dividing by zero'
    value = 99999999
    
value


Warning: dividing by zero
Out[5]:
99999999

In [6]:
# If an exception is raised in a function, the exception will propagate
# up the calling stack until there is an except clause to handle it, or
# it gets to the top of the stack, in which case the program will terminate.

def divide_by_zero(number):
    return number / 0

divide_by_zero(3)


---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-6-4d99884566b4> in <module>()
      6     return number / 0
      7 
----> 8 divide_by_zero(3)

<ipython-input-6-4d99884566b4> in divide_by_zero(number)
      4 
      5 def divide_by_zero(number):
----> 6     return number / 0
      7 
      8 divide_by_zero(3)

ZeroDivisionError: integer division or modulo by zero

In [18]:
try:
    value = divide_by_zero(23)
except:
    print 'Warning: dividing by zero'
    value = 99999999

value


Warning: dividing by zero
Out[18]:
99999999

In [26]:
def safe_divide_by_zero(number):
    try:
        return number / 0
    except:
        return 99999999

try:
    value = safe_divide_by_zero(23)
except:
    print 'Warning: dividing by zero'
    value = -1
    
value


Out[26]:
99999999

In [7]:
# you can have more than one "except" block and you can specify which
# class of exception each one handles. Whichever one is raised first
# will execute the appropriate except block. An except block that does
# not specify a class of exception (as seen above) will handle any class
# of exception

d = {
    'step 1': 'Learn Python',
    'step 2': 'Write some code',
    'step 3': 'Profit!'
}

def misbehave():
    value = 23 / 0
    step4 = d['step 4']
    return value, step4

misbehave()
print 'Successfully misbehaved'


---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-7-c94c4beb0961> in <module>()
     16     return value, step4
     17 
---> 18 misbehave()
     19 print 'Successfully misbehaved'

<ipython-input-7-c94c4beb0961> in misbehave()
     12 
     13 def misbehave():
---> 14     value = 23 / 0
     15     step4 = d['step 4']
     16     return value, step4

ZeroDivisionError: integer division or modulo by zero

In [24]:
try:
    misbehave()
except ZeroDivisionError:
    print 'Divided by zero'

print 'Successfully misbehaved'


Divided by zero
Successfully misbehaved

In [25]:
def misbehave2():
    step4 = d['step 4']
    value = 23 / 0
    return value, step4

try:
    misbehave2()
except ZeroDivisionError:
    print 'Divided by zero'

print 'Successfully misbehaved'


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-25-bb09075630b6> in <module>()
      5 
      6 try:
----> 7     misbehave2()
      8 except ZeroDivisionError:
      9     print 'Divided by zero'

<ipython-input-25-bb09075630b6> in misbehave2()
      1 def misbehave2():
----> 2     step4 = d['step 4']
      3     value = 23 / 0
      4     return value, step4
      5 

KeyError: 'step 4'

In [9]:
def misbehave3(numerator, denominator, key):
    value = numerator / denominator
    step = d[key]
    return value, step

try:
    value, step = misbehave3(23, 5, 'step 3')
    print value, step
except ZeroDivisionError:
    print 'Divided by zero'
except KeyError:
    print 'Missing key'


4 Profit!

In [10]:
try:
    value, step = misbehave3(23, 0, 'step 3')
    print value, step
except ZeroDivisionError:
    print 'Divided by zero'
except KeyError:
    print 'Missing key'


Divided by zero

In [12]:
try:
    value, step = misbehave3(23, 0, 'step 4')
    print value, step
except KeyError:
    print 'Missing key'
except ZeroDivisionError:
    print 'Divided by zero'


Divided by zero

In [36]:
# you can raise exceptions yourself. they don't have to be "true"
# and you can give a message that will be accessible when the exception
# is handled or it causes the program to terminate

value = 25 / 5
raise ZeroDivisionError('Just raising this because I can')


---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-36-debf23fc876c> in <module>()
      4 
      5 value = 25 / 5
----> 6 raise ZeroDivisionError('Just raising this because I can')

ZeroDivisionError: Just raising this because I can

In [14]:
# after handling an exception, you can re-raise it and it will continue
# propagating up the stack

try:
    value = 25 / 0
except ZeroDivisionError:
    print 'Got zero division error'
    raise


Got zero division error
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-14-63ba4a454f37> in <module>()
      1 try:
----> 2     value = 25 / 0
      3 except ZeroDivisionError:
      4     print 'Got zero division error'
      5     raise

ZeroDivisionError: integer division or modulo by zero