Skip to content

Exceptions

In python, exceptions are events that interrupt the normal flow of the program during its execution. They are errors that occur at runtime, unlike syntax errors that are detected before execution. Exceptions can be handled using the try-except block, which allows the program to continue its execution even if an error occurs.

Below are some of the most common exceptions you may encounter:

ExceptionDescription
SyntaxErrorOccurs when there is a syntax error in the code.
IndentationErrorThe code indentation is incorrect.
NameErrorAn attempt is made to use a variable that has not been defined.
TypeErrorAn operation is performed between incompatible data types.
ValueErrorA value has the correct type but is inappropriate for the operation.
IndexErrorIndex outside the valid range in a sequence as a list or tuple.
KeyErrorAn attempt is made to access a non-existent key in a dictionary.
AttributeErrorAn attempt is made to access an attribute that does not exist in the object.
ZeroDivisionErrorOccurs when dividing a number by zero.
ImportErrorIt is not possible to import a module or part of a module.
ModuleNotFoundErrorThe module you are trying to import is not found.
FileNotFoundErrorThe specified file does not exist.
IOErrorGeneral input/output error when working with files.
RuntimeErrorError detected at runtime.
StopIterationAn iterator has been exhausted.
OverflowErrorNumerical result too large to be represented.
MemoryErrorNot enough memory to perform an operation.
AssertionErrorThe condition of an assertion with assert has failed.
PermissionErrorYou do not have the necessary permissions to access the resource.

These exceptions are not all the ones that the language handles, but I will show you a script that can teach you all the available ones.

map.py
import builtins
# Filters out all built-in objects that are subclasses of BaseException
exceptions = [e for e in dir(builtins) if isinstance(getattr(builtins, e), type) and issubclass(getattr(builtins, e), BaseException)]
# Displays the complete list
for exc in exceptions:
print(exc)