Whenever an error is encountered in your program, Python will raise an exception stating the line number and what went wrong:
>>> x = [1,2,3] >>> x[10] Traceback (most recent call last): File " ", line 1, in x[10] IndexError: list index out of range
If we want the code to continue running, we can use a try/except block:
>>> x = [1,2,3] >>> try: >>> x[10] >>> except IndexError: >>> print "What are you trying to pull?" >>> print "Continuing program..."
Another variation is:
>>> x = [1,2,3] >>> try: >>> x[10] >>> except IndexError: >>> print "What are you trying to pull?" >>> else: # Will only run if no exception was raised >>> print "No exception was encountered" >>> print "Continuing program..."
You can raise your own exception if you want to prevent the script from running:
>>> if func() == "bad return value":
>>> raise RuntimeError("Something bad happened")
