CS 200: Exceptions

Video:

See Exceptions

Exceptions: EAFP vs LBYL

EAFP: easier to ask for forgiveness than permission (Perl programming language, per Larry Wall. See quotes of Larry Wall).

LBYL: look before you leap. Risk management philosophy at the heart of exceptions.

Try to anticipate things that can go wrong and mitigate the consequences. See https://stackoverflow.com/questions/11360858/what-is-the-eafp-principle-in-python. Note: good exam question.

Risk Management

Things can go wrong. Hope for the best, but expect the worst. In the words of the 20th century philosopher, Mike Tyson, everyone has a plan until they get punched in the face.

I spent years in finance as a risk manager. My job was to try to imagine things that could go wrong and take steps to mitigate, if not eliminate, those risks. Farmers sell their crops on future markets to hedge against price fluctuations. Airlines buy jet fuel on futures markets to hedge price risk. Multinational companies buy currency futures to hedge against foreign exchange risk. Farmers can also insure against bad weather, like drought. Homeowners buy insurance protecting them from fire, flood, theft, and vandalism. Some companies (but not many) had business interruption insurance that protected them against the covid-19 pandemic shutting down their business.

In each of the cases, there is a foreseeable, but uncertain, adverse event:

Investors can hedge their stock market investments using options. A call option pays off if the price of a stock goes up. A put option pays off if the price of a stock goes down. Many investors use combinations of options to protect their portfolios from uncertain future events.

In the words of another twentieth century philosopher, Yogi Berra, it is difficult to make predictions, especially about the future.

Reading

List of built-in exceptions

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

ZeroDivisionError: division by zero

NameError: name 'a' is not defined

IndexError: list index out of range

NameError: name 'foo' is not defined

FileNotFoundError: [Errno 2] No such file or directory: 'foo'

ImportError: No module named 'foo' (may appear as ModuleNotFoundError)

KeyError: 'key'

PermissionError: [Errno 13] Permission denied: '/hello'

RuntimeError: maximum recursion depth exceeded

AttributeError: 'range' object has no attribute 'next'

TypeError: 'range' object is not an iterator

StopIteration

UnboundLocalError: local variable 'x' referenced before assignment

user defined exceptions

TypeError: this is a mistake

handling exceptions with try / except

Another try/except example

like counttags() in homework

sys.exc_info() returns information about the state of execution

f20(1) => AssertionError

The assert() function can be used to monitor the execution of the program. At any point, the programmer can assert statements that should be true. If the statement is not true, assert will raise an exception.

Below we assert that the input parameter, x, is even.

errno module can translate error numbers

There are lots of possible errors.

Decorator for Exception Handling

The following three functions each handles a TypeError exception. See https://medium.com/swlh/handling-exceptions-in-python-a-cleaner-way-using-decorators-fae22aa0abec

We can define a decorator and apply it to each function.

Logging Exceptions

See https://www.blog.pythonlibrary.org/2016/06/09/python-how-to-create-an-exception-logging-decorator/

The logging module provides a uniform process for logging code events. See https://docs.python.org/3/howto/logging.html

Here is an example.

Create a decorator to log exceptions

End of Exceptions notebook