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.
except
block and that the try
clause contains an error.Here's an example:
1 2 3 4 5 6 7 8
a = 5 b = 0 try: quotient = a / b print(quotient) except Exception as X: print(X)
Reminder
True
while None
and 0
are False
.
try | try is a Python keyword that enables you to test a code block for errors. |
---|---|
except | except is a Python keyword that is used to handle exceptions arising in the previous try clause. |
if | if 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. |
else | The 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
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.
Exception | Explanation |
---|---|
BaseException | Base class for all built-in exceptions. |
Exception | All built in exceptions are derived from the Exception class (other than system-exiting exceptions.) Use this class to derive user-defined exceptions. |
args | The 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. |
BufferError | Exception raised when a buffer operation cannot be executed. You can learn more about buffers in Python’s buffer protocol documentation. |
ArithmeticError | Base class for arithmetic errors. |
LookupError | Base 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 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.
Exception | Explanation | Hierarchy |
---|---|---|
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 . |
KeyboardInterrupt | Raised 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 . |
GeneratorExit | Raised upon closing a generatoror coroutine. | Inherits directly from BaseException rather than Exception because Python does not technically consider it to be an error. |
StopIteration | Raised by next() and the iterator’s __next__() method. Signals that the iterator will not produce any more items. | Inherits from Exception . |
StopAsyncIteration | Raised by asynchronous iterator’s __anext__() method. | Inherits from Exception . |
AssertionError | When an assert statement fails, this Python exception is raised. | Inherits from Exception . |
AttributeError | When an attribute referenceor assignment fails, this Python exception is raised. | Inherits from Exception . |
EOFError | EOF stands for end-of-file. This exception is raised when an input() function reaches an EOF condition without reading any data. | Inherits from Exception . |
ImportError | Raised 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 . |
ModuleNotFoundError | Also raised by import. Occurs when a module cannot be located or when none is found in sys.modules. | Inherits from Exception and is a subclass of ImportError . |
OverflowError | Raised 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 . |
ZeroDivisionError | Python 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 . |
IndexError | This exception occurs if a sequence subscript is out of range. | Inherits from Exception . |
KeyError | Raised when a mapping key or, dictionary key, is not found in the existing set of keys. | Inherits from Exception . |
MemoryError | Raised when there is not enough memory for the current operation. This exception can be addressed by deleting other objects. | Inherits from Exception . |
NameError | When 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 . |
UnboundLocalError | Raised when a local variable without value (in a function or method) is referenced. | Inherits from Exception and is a subclass of NameError . |
OSError | Raised when a system-related error is returned by a system function. | Inherits from Exception . Has several subclasses beneath it known as OS exceptions. |
BlockingIOError | If 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_written | An 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 . |
ChildProcessError | If an operation on a child process fails, this exception will be raised. | Inherits from Exception and belongs to the subclass of OS exceptions. |
FileExistsError | Creating a directory or file that already exists will raise this exception. | Inherits from Exception and belongs to the subclass of OS exceptions. |
FileNotFoundError | Requesting a directory or file that does not exist raises this exception. | Inherits from Exception and belongs to the subclass of OS exceptions. |
InterruptedError | When an incoming signal interrupts a system call, Python raises this exception. | Inherits from Exception and belongs to the subclass of OS exceptions. |
IsADirectoryError | Raised if a file operation is requested on a directory—for example, os.remove() . | Inherits from Exception and belongs to the subclass of OS exceptions. |
NotADirectoryError | Raised 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. |
PermissionError | This 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. |
ProcessLookupError | When a process does not exist, Python raises this exception. | Inherits from Exception and belongs to the subclass of OS exceptions. |
TimeoutError | When a system function times out at the system level, this exception is raised. | Inherits from Exception and belongs to the subclass of OS exceptions. |
ConnectionError | Base class for issues related to connection. | Inherits from Exception , belongs to the subclass of OS exceptions. |
BrokenPipeError | Raised 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. |
ConnectionAbortedError | When a peer aborts a connection attempt, Python raises this exception. | Inherits from Exception and belongs to the ConnectionError subclass of OS exceptions. |
ConnectionRefusedError | When a peer refuses a connection attempt, Python raises this exception. | Inherits from Exception and belongs to the ConnectionError subclass of OS exceptions. |
ConnectionResetError | When a peer resets a connection attempt, Python raises this exception. | Inherits from Exception and belongs to the ConnectionError subclass of OS exceptions. |
ReferenceError | Raised 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 . |
RuntimeError | Raised when the detected error does not fall into any other category. | Inherits from Exception . |
NotImplementedError | This 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 . |
RecursionError | When the interpreter detects that the maximum recursion depth has been reached, Python raises this exception. | Inherits from Exception and is derived from RuntimeError . |
SystemError | Raised 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 . |
TypeError | If an operation or function is applied to an object of improper type, Python raises this exception. | Inherits from Exception . |
ValueError | Raised 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 . |
UnicodeError | Raised when the encoding or decoding of a Unicode error occurs. | Inherits from Exception and is derived from ValueError . |
UnicodeDecodeError | Raised during decoding when a Unicode error occurs. | Inherits from Exception and belongs to the UnicodeError subclass. |
UnicodeEncodeError | Raised during encoding when a Unicode error occurs. | Inherits from Exception and belongs to the UnicodeError subclass. |
UnicodeTranslateError | Raised during translating when a Unicode error occurs. | Inherits from Exception and belongs to the UnicodeError subclass. |
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.
Exception | Explanation | Hierarchy |
---|---|---|
Warning | Base class for each warning category class. | Inherits from Exception . |
DeprecationWarning | Category for deprecated feature warnings that are intended for other developers. | Inherits from Exception and belongs to the Warning class. |
PendingDeprecationWarning | Category for future deprecated features. These exceptions are ignored by default. | Inherits from Exception and belongs to the Warning class. |
RuntimeWarning | Category for hesitant runtime-related features. | Inherits from Exception and belongs to the Warning class. |
SyntaxWarning | Category for hesitant syntactic-related features. | Inherits from Exception and belongs to the Warning class. |
UserWarning | Default category for warn() . | Inherits from Exception and belongs to the Warning class. |
FutureWarning | Category for deprecated feature warnings that are intended for end users of Python applications. | Inherits from Exception and belongs to the Warning class. |
ImportWarning | Category 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. |
UnicodeWarning | Category for Unicode-related warnings. | Inherits from Exception and belongs to the Warning class. |
BytesWarning | Category for bytearrayand bytesrelated warnings. | Inherits from Exception and belongs to the Warning class. |
ResourceWarning | Category 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.
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.