#!/usr/bin/env python # coding: utf-8 # # Raising Errors # # It is possible to tell Python to generate an error. This is useful if you want to verify input to a function or stop your code running when something happens that your code does not know how to process. # Take this very simple function for example. This function is only designed to be used with numbers, so we want to make sure we dont pass a string. # In[ ]: # The function works as expected with a number: # In[ ]: # When it is passed a string it raises an error, telling the user that the argument x can not be a string. # In[ ]: # You can raise many different kinds of exception, however `ValueError` is generally the most useful. Other useful types of error are: # In[ ]: # In[ ]: # #
#
#

What Type of Error?

#
# # #
# #

The example above:

#
def square(x):
#     if isinstance(x, str):
#         raise ValueError("x can not be a string")
#     else:
#         return x**2
# 
# # #

uses ValueError, what type of error would be more appropriate?

# #
# #
# # #
#
#

Solution

#
# # #
# #

TypeError should be raised when the type (i.e. str, float, int) is incorrect.

# #
# #
# # ## Silent Errors # # Not all programming errors raise an exception, some are errors in the functioning of the code. i.e. this: # In[ ]: # In[ ]: # This is obviously incorrect, but Python does not know any difference, it executes the code as written and returns a result. # # Most logical errors or "bugs" like this are not so easy to spot! As the complexity of your code increases the odds that mistakes and errors creep in increases. The best way to detect and prevent this kind of error is by writing tests.