Q4

Exception handling.

A

In this question, you'll write an error handler for a function that almost always fails, will_it_blend.

Your function will be called will_it_blend_safely

  • takes no arguments
  • returns True if will_it_blend doesn't throw any exceptions, False otherwise

You cannot use any built-in Python functions.


In [ ]:
import numpy as np

def will_it_blend():
    errors = [ValueError, AssertionError, AttributeError, ImportError, IndexError, KeyError, NameError, RuntimeError, TypeError]
    error_index = np.random.randint(0, len(errors) + 1)
    if error_index == len(errors):
        return 0
    else:
        raise errors[error_index]
        
# Don't touch anything above this line.
# YOUR FUNCTION HERE

### BEGIN SOLUTION

### END SOLUTION

In [ ]:
np.random.seed(4545)
for i in range(5):
    assert not will_it_blend_safely()
assert will_it_blend_safely()

np.random.seed(574738)
assert will_it_blend_safely()

B

In this question, you'll write a new function, will_it_blend_more_safely, which changes its behavior based on the specific error that will_it_blend throws.

  • takes a variable number of arguments: names of Python errors
  • returns True if will_it_blend throws an error, AND that error is included in the argument list of will_it_blend_more_safely; False otherwise

You won't derive any help from using your solution in Part A; you're implementing a function that's similar but doesn't use the same underlying principle.

You can't use any built-in Python functions.


In [ ]:


In [ ]:
np.random.seed(84552)
assert not will_it_blend_more_safely(ZeroDivisionError, AttributeError)
assert will_it_blend_more_safely(AttributeError, NameError, UnicodeError)

np.random.seed(75284)
assert will_it_blend_more_safely(KeyError, NameError, RuntimeError, TypeError)
assert will_it_blend_more_safely(KeyError, NameError, RuntimeError, TypeError)
assert not will_it_blend_more_safely(KeyError, NameError, RuntimeError, TypeError)