Lesson 9
No Object is an Island
Chapter 9: Exception handling
Built-in Exceptions
Below is the list of all Python built-in exceptions (reproduced from the official documentation).
All built-in exceptions are special instances of BaseException
, and is arranged in a class hierarchy. So Exception
is a special kind of BaseException
, ZeroDivisionError
is a special kind of ArithmeticError
, etc. We will discuss more about class hierarchy in the next lesson.
You may have already encountered some of these exceptions. How many of these classes do you recognise?
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
| +-- ModuleNotFoundError
+-- 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
Try skimming through the documentation for more details about these Exceptions. Some Exceptions that you might encounter often include ModuleNotFoundError
, TypeError
, ValueError
, IndexError
(e.g. trying to access a list element that is beyond the size of the list), KeyError
(e.g. accessing a dictionary element with an invalid key), FileNotFoundError
, and one of the ArithmeticError
s. Understanding what these exceptions represent will enable you to debug your code better in the future.
You are also encouraged to choose a semantically suitable Exception
if you are raising your own exceptions.