Python Exception Handling Cheat Sheet

Written by Coursera • Updated on

We recommend using this cheat sheet as reference material rather than a memorization tool. As you continue to practice, you will learn to recognize and handle common exceptions on your own.


How to print a python exception in 3 steps

  1. Make sure you’re inside the except block and that the try clause contains an error.
  2. Define the exception.
  3. Use the print() function.

Here's an example:

PYTHON
1
2
3
4
5
6
7
8
a = 5
b = 0

try:
    quotient = a / b
    print(quotient)
except Exception as X:
    print(X)

Python exception handling statements

Reminder

Python interprets non-zero values as True while None and 0 are False.
trytry is a Python keyword that enables you to test a code block for errors.
exceptexcept is a Python keyword that is used to handle exceptions arising in the previous try clause.
ifif is a common conditional statement. It dictates whether a statement should be executed or not by checking for a given condition. If the condition is true, the if block of code will be executed.
elseThe else statement contains the block of code that will execute if the condition from the if statement is false or resolves to zero.

Learn more about conditional statements in the following tutorial: How to Use a Python If Else Statement

7 base classes

The following chart covers Python exception base classes. Base classes are exceptions that establish the basis of other exceptions. These are not to be inherited by user-defined classes.

ExceptionExplanation
BaseExceptionBase class for all built-in exceptions.
ExceptionAll built in exceptions are derived from the Exception class (other than system-exiting exceptions.) Use this class to derive user-defined exceptions.
argsThe tuple of arguments that is given to the constructor. A “tuple” is an ordered set of values that is used to store multiple items in just one variable.
with_traceback(tb)An alternate traceback display function. Used to return the exception object and set tb as the new traceback for the exception.
BufferErrorException raised when a buffer operation cannot be executed. You can learn more about buffers in Python’s buffer protocol documentation.
ArithmeticErrorBase class for arithmetic errors.
LookupErrorBase class for exceptions that are raised as a result of the use of an invalid key or index on a mapping or sequence.

Other exceptions

Other exceptions are known as concrete exceptions. These are raised most commonly and may have additional subclasses beneath them. The chart below defines each concrete exception as well as the base class and the subclasses they belong to. These can be inherited by user-defined exceptions.

ExceptionExplanationHierarchy
SystemExit
Raised by sys.exit()function. When left unhandled, the interpreter exits without printing a stack trace. Inherits from BaseException to avoid being unintentionally caught by code that catches Exception.
KeyboardInterruptRaised when an interrupt key (such as Delete or Control-C) is hit by the user. This exception is notable because it may be raised unpredictably, leaving the program running in an inconsistent state. It is recommended to avoid raising this error. If it is raised, allow it to end the program immediately.Inherits from BaseException to avoid being unintentionally caught by code that catches Exception.
GeneratorExitRaised upon closing a generatoror coroutineInherits directly from BaseException rather than Exception because Python does not technically consider it to be an error. 
StopIterationRaised by next()and the iterator’s __next__()method. Signals that the iterator will not produce any more items. Inherits from Exception.
StopAsyncIterationRaised by asynchronous iterator’s  __anext__() method. Inherits from Exception.
AssertionErrorWhen an assert statement fails, this Python exception is raised. Inherits from Exception.
AttributeErrorWhen an attribute referenceor assignment fails, this Python exception is raised. Inherits from Exception.
EOFErrorEOF stands for end-of-file. This exception is raised when an input() function reaches an EOF condition without reading any data.Inherits from Exception.
ImportErrorRaised when an import statement struggles to load a module. Can also be raised when a “from list” in from...import includes a name it cannot find.Inherits from Exception.
ModuleNotFoundErrorAlso raised by import. Occurs when a module cannot be located or when none is found in sys.modulesInherits from Exception and is a subclass of ImportError.
OverflowErrorRaised when the result of an arithmetic operation is too large or the integers are outside of a required range. Inherits from Exception and is a subclass of ArithmeticError.
ZeroDivisionErrorPython raises this type of error when the second argument of a modulo operation or a division is 0. Inherits from Exception and is a subclass of ArithmeticError.
IndexErrorThis exception occurs if a sequence subscript is out of range.Inherits from Exception.
KeyErrorRaised when a mapping key or, dictionary key, is not found in the existing set of keys.Inherits from Exception.
MemoryErrorRaised when there is not enough memory for the current operation. This exception can be addressed by deleting other objects. Inherits from Exception.
NameErrorWhen a global or local name cannot be found, this type of error is raised. The conditions for this exception only apply to unqualified names. Inherits from Exception.
UnboundLocalErrorRaised when a local variable without value (in a function or method) is referenced.Inherits from Exception and is a subclass of NameError.
OSErrorRaised when a system-related error is returned by a system function. Inherits from Exception. Has several subclasses beneath it known as OS exceptions. 
BlockingIOErrorIf an operation would block on an object that is set for non-blocking operation, this exception will be raised. Inherits from Exception and belongs to the subclass of OS exceptions. Has an additional attribute: characters_written.
characters_writtenAn integer. This attribute contains the number of characters that was written to the stream prior to it blocking.Inherits from Exception, is a subclass of OS exceptions, and an attribute of BlockingIOError.
ChildProcessErrorIf an operation on a child process fails, this exception will be raised. Inherits from Exception and belongs to the subclass of OS exceptions.
FileExistsErrorCreating a directory or file that already exists will raise this exception.Inherits from Exception and belongs to the subclass of OS exceptions.
FileNotFoundErrorRequesting a directory or file that does not exist raises this exception.Inherits from Exception and belongs to the subclass of OS exceptions.
InterruptedErrorWhen an incoming signal interrupts a system call, Python raises this exception.Inherits from Exception and belongs to the subclass of OS exceptions.
IsADirectoryErrorRaised if a file operation is requested on a directory—for example, os.remove().Inherits from Exception and belongs to the subclass of OS exceptions.
NotADirectoryErrorRaised if a directory operation is requested on anything that isn’t a directory. May also be raised if an operation attempts to open or cross a file that isn’t a directory as if it were a directory. Inherits from Exception and belongs to the subclass of OS exceptions.
PermissionErrorThis exception is raised when attempting to run an operation without the proper permissions or access rights. Inherits from Exception and belongs to the subclass of OS exceptions.
ProcessLookupErrorWhen a process does not exist, Python raises this exception.Inherits from Exception and belongs to the subclass of OS exceptions.
TimeoutErrorWhen a system function times out at the system level, this exception is raised. Inherits from Exception and belongs to the subclass of OS exceptions.
ConnectionErrorBase class for issues related to connection.Inherits from Exception, belongs to the subclass of OS exceptions.
BrokenPipeErrorRaised when attempting to write on a pipe whose other end is closed. Can also be raised when attempting to write on a socket shutdown for writing. Inherits from Exception and belongs to the ConnectionError subclass of OS exceptions.
ConnectionAbortedErrorWhen a peer aborts a connection attempt, Python raises this exception. Inherits from Exception and belongs to the ConnectionError subclass of OS exceptions.
ConnectionRefusedErrorWhen a peer refuses a connection attempt, Python raises this exception. Inherits from Exception and belongs to the ConnectionError subclass of OS exceptions.
ConnectionResetErrorWhen a peer resets a connection attempt, Python raises this exception. Inherits from Exception and belongs to the ConnectionError subclass of OS exceptions.
ReferenceErrorRaised when the weakref.proxy() function creates a weak reference proxy that is used to access the referent’s attribute after it has already been garbage collected. Inherits from Exception.
RuntimeErrorRaised when the detected error does not fall into any other category. Inherits from Exception.
NotImplementedErrorThis exception is raised in user-defined base classes when they require derived classes in order to override the method. Can also be raised while the class is in development to demonstrate the requirement of the real implementation to be added. Inherits from Exception and is derived from RuntimeError.
RecursionErrorWhen the interpreter detects that the maximum recursion depth has been reached, Python raises this exception. Inherits from Exception and is derived from RuntimeError.
SystemErrorRaised when the interpreter detects an internal error that can be addressed. It is recommended to report the exception, version of the interpreter (sys.version), source of the program, and the error message with the exception’s associated value to the author or Python interpreter maintainer. Inherits from Exception.
TypeErrorIf an operation or function is applied to an object of improper type, Python raises this exception.Inherits from Exception.
ValueErrorRaised when an operation or function receives the right type of argument but the wrong value and it cannot be matched by a more specific exception.Inherits from Exception.
UnicodeErrorRaised when the encoding or decoding of a Unicode error occurs.Inherits from Exception and is derived from ValueError.
UnicodeDecodeErrorRaised during decoding when a Unicode error occurs.Inherits from Exception and belongs to the UnicodeError subclass.
UnicodeEncodeErrorRaised during encoding when a Unicode error occurs.Inherits from Exception and belongs to the UnicodeError subclass.
UnicodeTranslateErrorRaised during translating when a Unicode error occurs.Inherits from Exception and belongs to the UnicodeError subclass.

Warnings

The built-in Python exceptions below are categorized as warnings. This grouping enables you to filter out groups of warnings whenever necessary. If you need to define additional warning categories, subclass one of the categories below. Ensure it remains a subclass of the Warning class.

ExceptionExplanationHierarchy
WarningBase class for each warning category class.Inherits from Exception.
DeprecationWarningCategory for deprecated feature warnings that are intended for other developers.Inherits from Exception and belongs to the Warning class.
PendingDeprecationWarningCategory for future deprecated features. These exceptions are ignored by default. Inherits from Exception and belongs to the Warning class.
RuntimeWarningCategory for hesitant runtime-related features. Inherits from Exception and belongs to the Warning class.
SyntaxWarningCategory for hesitant syntactic-related features. Inherits from Exception and belongs to the Warning class.
UserWarningDefault category for warn().Inherits from Exception and belongs to the Warning class.
FutureWarningCategory for deprecated feature warnings that are intended for end users of Python applications.Inherits from Exception and belongs to the Warning class.
ImportWarningCategory for warnings that are triggered during the import process for a module. These exceptions are ignored by default. Inherits from Exception and belongs to the Warning class.
UnicodeWarningCategory for Unicode-related warnings.Inherits from Exception and belongs to the Warning class.
BytesWarningCategory for bytearrayand bytesrelated warnings. Inherits from Exception and belongs to the Warning class.
ResourceWarningCategory for resource usage-related warnings. These exceptions are ignored by default. Inherits from Exception and belongs to the Warning class.

Stay up to date on Python releases and tips by getting involved with the Python community. Try subscribing to the free Python email newsletter or connecting with your peers on the Python programming Slack channel.


Written by Coursera • Updated on

This content has been made available for informational purposes only. Learners are advised to conduct additional research to ensure that courses and other credentials pursued meet their personal, professional, and financial goals.

Learn without limits