Exceptions

In [1]:
d = {"a": 42, "b": 37, "c": 7}
In [3]:
d["z"]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-3-31f9b394b368> in <module>()
----> 1 d["z"]

KeyError: 'z'
In [23]:
def access_dictionary(d, k):
    return d[k]

def print_values(d, keys):
    for k in keys:
        value = access_dictionary(d, k)
        print(k, value)

def go():
    d = {"a": 42, "b": 37, "c": 7}

    print_values(d, ["a","b"])

    print_values(d, ["a","z"])
In [24]:
go()
a 42
b 37
a 42
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-24-43efa8e286a7> in <module>()
----> 1 go()

<ipython-input-23-5e9031ec14ae> in go()
     12     print_values(d, ["a","b"])
     13 
---> 14     print_values(d, ["a","z"])

<ipython-input-23-5e9031ec14ae> in print_values(d, keys)
      4 def print_values(d, keys):
      5     for k in keys:
----> 6         value = access_dictionary(d, k)
      7         print(k, value)
      8 

<ipython-input-23-5e9031ec14ae> in access_dictionary(d, k)
      1 def access_dictionary(d, k):
----> 2     return d[k]
      3 
      4 def print_values(d, keys):
      5     for k in keys:

KeyError: 'z'
In [25]:
def access_dictionary(d, k):
    try:
        return d[k]
    except KeyError:
        return -1 # <-- Arbitrary default value
In [26]:
go()
a 42
b 37
a 42
z -1
In [17]:
try:
    with open("names.txt") as f:
        print(f.read())    
except IOError as err:
    print(err)
[Errno 2] No such file or directory: 'names.txt'
In [35]:
def divide(a, b):
    return a / b
In [39]:
try:
    x = divide(5, 0)
    print("x is", x)
except ZeroDivisionError as err:
    print("Division by zero!")
Division by zero!
In [40]:
try:
    x = divide(5, "foo")
    print("x is", x)
except ZeroDivisionError as err:
    print("Division by zero!")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-40-37969a0ba51f> in <module>()
      1 try:
----> 2     x = divide(5, "foo")
      3     print("x is", x)
      4 except ZeroDivisionError as err:
      5     print("Division by zero!")

<ipython-input-35-5c74f9fd7706> in divide(a, b)
      1 def divide(a, b):
----> 2     return a / b

TypeError: unsupported operand type(s) for /: 'int' and 'str'
In [42]:
try:
    x = divide(5, "foo")   
    print("x is", x)
except TypeError as err:
    print(err)
except ZeroDivisionError:
    print("Division by zero!")
unsupported operand type(s) for /: 'int' and 'str'
In [47]:
try:
    x = divid(6, 2)   
    print("x is", x)
except TypeError as err:
    print(err)
except ZeroDivisionError:
    print("Division by zero!")
except Exception as e:
    print("Unexpected Error:", e)
Unexpected Error: name 'divid' is not defined
In [49]:
def safe_divide(a,b):
    try:
        x = divide(a, b)   
        print("x is", x)
    except TypeError as err:
        print(err)
    except ZeroDivisionError:
        print("Division by zero!")
    except Exception as e:
        print("Unexpected Error:", e)
    finally:
        print("divide() was called with {} and {}".format(a, b))
In [50]:
safe_divide(6,2)
x is 3.0
divide() was called with 6 and 2
In [51]:
safe_divide(6,0)
Division by zero!
divide() was called with 6 and 0
In [52]:
safe_divide(6, "foo")
unsupported operand type(s) for /: 'int' and 'str'
divide() was called with 6 and foo