English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
When Python (interpreter) encounters an error, it raises an exception. For example: division by zero. In this article, you will learn about the different built-in exception handling in Python.
When writing programs, we often encounter errors.
Errors caused by not following the correct structure (syntax) of the language are called syntax errors or parsing errors.
>>> if a < 3 File '<interactive input>', line 1 if a < 3 ^ SyntaxError: invalid syntax
Here we can notice that there is a colon missing in the if statement.
Errors may also occur at runtime, which are called exceptions. For example, when the file we try to open does not exist (FileNotFoundError), when we divide a number by zero (ZeroDivisionError), or when we cannot find the module we try to import (ImportError), such situations occur.
Each time this type of runtime error occurs, Python creates an exception object. If not handled properly, it will output the traceback of the error and some detailed information about the cause of the error.
>>> 1 / 0 Traceback (most recent call last): File '<string>', line 301, in runcode File '<interactive input>', line 1, in <module> ZeroDivisionError: division by zero >>> open('imaginary.txt') Traceback (most recent call last): File '<string>', line 301, in runcode File '<interactive input>', line 1, in <module> FileNotFoundError: [Errno 2] No such file or directory: 'imaginary.txt'
Illegal operations may raise exceptions. There are many built-in exceptions in Python, which are raised when the corresponding errors occur. We can use the local() built-in function to view all built-in exceptions, as shown below.
>>> locals()['__builtins__']
This will return a dictionary of built-in exceptions, functions, and properties.
The following lists some common built-in exceptions in Python programming and the errors that cause them.
Exception | Error cause |
---|---|
AssertionError | Thrown when an assert statement fails. |
AttributeError | Thrown when an attribute assignment or reference fails. |
EOFError | Thrown when the input() function reaches the end of file condition. |
FloatingPointError | Thrown when a floating-point operation fails. |
GeneratorExit | Thrown when a generator method is called on close(). |
ImportError | Thrown when the imported module is not found. |
IndexError | Thrown when the index of a sequence is out of range. |
KeyError | Thrown when a key is not found in the dictionary. |
KeyboardInterrupt | When the user presses the interrupt key (Ctrl + Thrown when attempting to call a method on c or Delete). |
MemoryError | Thrown when there is not enough memory to perform an operation. |
NameError | Thrown when a variable is not found locally or globally. |
NotImplementedError | An unimplemented method. |
OSError | Triggered when system operations cause system-related errors |
OverflowError | Triggered when the result of an arithmetic operation is too large to be represented |
ReferenceError | Triggered when accessing garbage-collected reference objects through weak reference proxies |
RuntimeError | Triggered when an error does not belong to any other category |
StopIteration | Triggered by the next() function to indicate that the iterator has no other items to return |
SyntaxError | Triggered by the parser when a syntax error is encountered |
IndentationError | Triggered when indentation is incorrect |
TabError | Triggered when indentation is composed of inconsistent tabs and spaces |
SystemError | Triggered when the interpreter detects an internal error |
SystemExit | Triggered by the sys.exit() function |
TypeError | Triggered when a function or operation is applied to an object of the wrong type |
UnboundLocalError | Triggered when a reference to a local variable in a function or method is made without a value bound to the variable |
UnicodeError | Triggered when encoding or decoding errors related to Unicode occur |
UnicodeEncodeError | Triggered when Unicode-related errors occur during encoding |
UnicodeDecodeError | Triggered when Unicode-related errors occur during decoding |
UnicodeTranslateError | Triggered when Unicode-related errors occur during translation |
ValueError | Triggered when the function receives a parameter of the correct type but with an incorrect value |
ZeroDivisionError | Triggered when the second operand of division or modulus operation is zero |
We can also define our own exceptions in Python (if needed). Visit this page to learn more aboutUser-defined exceptionsMore information.
We can use try, except, and finally statementsHandle these built-in and user-defined exceptions in Python.