English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Knowledge of Python

Python Reference Manual

Python Errors and Built-in Exceptions

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'

Built-in exceptions

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.

Built-in standard exceptions of Python
ExceptionError cause
AssertionErrorThrown when an assert statement fails.
AttributeErrorThrown when an attribute assignment or reference fails.
EOFErrorThrown when the input() function reaches the end of file condition.
FloatingPointErrorThrown when a floating-point operation fails.
GeneratorExitThrown when a generator method is called on close().
ImportErrorThrown when the imported module is not found.
IndexErrorThrown when the index of a sequence is out of range.
KeyErrorThrown when a key is not found in the dictionary.
KeyboardInterruptWhen the user presses the interrupt key (Ctrl + Thrown when attempting to call a method on c or Delete).
MemoryErrorThrown when there is not enough memory to perform an operation.
NameErrorThrown when a variable is not found locally or globally.
NotImplementedErrorAn unimplemented method.
OSErrorTriggered when system operations cause system-related errors
OverflowErrorTriggered when the result of an arithmetic operation is too large to be represented
ReferenceErrorTriggered when accessing garbage-collected reference objects through weak reference proxies
RuntimeErrorTriggered when an error does not belong to any other category
StopIterationTriggered by the next() function to indicate that the iterator has no other items to return
SyntaxErrorTriggered by the parser when a syntax error is encountered
IndentationErrorTriggered when indentation is incorrect
TabErrorTriggered when indentation is composed of inconsistent tabs and spaces
SystemErrorTriggered when the interpreter detects an internal error
SystemExitTriggered by the sys.exit() function
TypeErrorTriggered when a function or operation is applied to an object of the wrong type
UnboundLocalErrorTriggered when a reference to a local variable in a function or method is made without a value bound to the variable
UnicodeErrorTriggered when encoding or decoding errors related to Unicode occur
UnicodeEncodeErrorTriggered when Unicode-related errors occur during encoding
UnicodeDecodeErrorTriggered when Unicode-related errors occur during decoding
UnicodeTranslateErrorTriggered when Unicode-related errors occur during translation
ValueErrorTriggered when the function receives a parameter of the correct type but with an incorrect value
ZeroDivisionErrorTriggered 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.