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:
Exception | Description |
---|---|
SyntaxError | Occurs when there is a syntax error in the code. |
IndentationError | The code indentation is incorrect. |
NameError | An attempt is made to use a variable that has not been defined. |
TypeError | An operation is performed between incompatible data types. |
ValueError | A value has the correct type but is inappropriate for the operation. |
IndexError | Index outside the valid range in a sequence as a list or tuple. |
KeyError | An attempt is made to access a non-existent key in a dictionary. |
AttributeError | An attempt is made to access an attribute that does not exist in the object. |
ZeroDivisionError | Occurs when dividing a number by zero. |
ImportError | It is not possible to import a module or part of a module. |
ModuleNotFoundError | The module you are trying to import is not found. |
FileNotFoundError | The specified file does not exist. |
IOError | General input/output error when working with files. |
RuntimeError | Error detected at runtime. |
StopIteration | An iterator has been exhausted. |
OverflowError | Numerical result too large to be represented. |
MemoryError | Not enough memory to perform an operation. |
AssertionError | The condition of an assertion with assert has failed. |
PermissionError | You 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.
import builtins
# Filters out all built-in objects that are subclasses of BaseExceptionexceptions = [e for e in dir(builtins) if isinstance(getattr(builtins, e), type) and issubclass(getattr(builtins, e), BaseException)]
# Displays the complete listfor exc in exceptions:print(exc)