Python Built-in Exceptions
In Python, exceptions are events that can alter the flow of control in a program. These errors can arise during program execution and need to be handled appropriately. Python provides a set of built-in exceptions, each meant to signal a particular type of error.
We can catch exceptions using try and except blocks, allowing your program to continue running even if an error occurs. These built-in exceptions can be viewed using the local() built-in functions as follows :
>>> locals()['__builtins__']
This returns a dictionary of built-in exceptions, functions and attributes.
Python Built-in Exceptions
Here’s a table listing all the major Python built-in exceptions along with a brief :
Exception Name | Description |
---|---|
BaseException | The base class for all built-in exceptions. |
Exception | The base class for all non-exit exceptions. |
ArithmeticError | Base class for all errors related to arithmetic operations. |
ZeroDivisionError | Raised when a division or modulo operation is performed with zero as the divisor. |
OverflowError | Raised when a numerical operation exceeds the maximum limit of a data type. |
FloatingPointError | Raised when a floating-point operation fails. |
AssertionError | Raised when an assert statement fails. |
AttributeError | Raised when an attribute reference or assignment fails. |
IndexError | Raised when a sequence subscript is out of range. |
KeyError | Raised when a dictionary key is not found. |
MemoryError | Raised when an operation runs out of memory. |
NameError | Raised when a local or global name is not found. |
OSError | Raised when a system-related operation (like file I/O) fails. |
TypeError | Raised when an operation or function is applied to an object of inappropriate type. |
ValueError | Raised when a function receives an argument of the right type but inappropriate value. |
ImportError | Raised when an import statement has issues. |
ModuleNotFoundError | Raised when a module cannot be found. |
IOError | Raised when an I/O operation (like reading or writing to a file) fails. |
FileNotFoundError | Raised when a file or directory is requested but cannot be found. |
StopIteration | Raised when the next() function is called and there are no more items in an iterator. |
KeyboardInterrupt | Raised when the user presses Ctrl+C or interrupts the program’s execution. |
SystemExit | Raised when the sys.exit() function is called to exit the program. |
NotImplementedError | Raised when an abstract method that needs to be implemented is called. |
RuntimeError | Raised when a general error occurs in the program. |
RecursionError | Raised when the maximum recursion depth is exceeded. |
SyntaxError | Raised when there is an error in the syntax of the code. |
IndentationError | Raised when there is an indentation error in the code. |
TabError | Raised when the indentation consists of inconsistent use of tabs and spaces. |
UnicodeError | Raised when a Unicode-related encoding or decoding error occurs. |
Let’s understand each exception in detail:
1. BaseException
The base class for all built-in exceptions. Example:
try:
raise BaseException("This is a BaseException")
except BaseException as e:
print(e)
Output
This is a BaseException
Explanation: This code manually raises a BaseException
and catches it, printing the exception message.
2. Exception
The base class for all non-exit exceptions. Example:
try:
raise Exception("This is a generic exception")
except Exception as e:
print(e)
Output
This is a generic exception
Explanation: This raises a generic Exception
and handles it, printing the message.
3. ArithmeticError
Base class for all errors related to arithmetic operations. Example:
try:
raise ArithmeticError("Arithmetic error occurred")
except ArithmeticError as e:
print(e)
Output
Arithmetic error occurred
Explanation: This raises an ArithmeticError
and catches it, displaying the error message.
4. ZeroDivisionError
Raised when a division or modulo operation is performed with zero as the divisor. Example:
try:
result = 10 / 0
except ZeroDivisionError as e:
print(e)
Output
division by zero
Explanation: This code attempts to divide by zero, causing a ZeroDivisionError
.
5. OverflowError
Raised when a numerical operation exceeds the maximum limit of a data type. Example:
import math
try:
result = math.exp(1000) # Exponential function with a large argument
except OverflowError as e:
print(e)
Output
math range error
Explanation: The exponential function with a large argument causes an OverflowError
.
6. FloatingPointError
Raised when a floating-point operation fails. Example:
import sys
import math
sys.float_info.max = 1.79e+308 # Maximum float value
try:
math.sqrt(-1.0) # This doesn't raise a FloatingPointError by default
except FloatingPointError as e:
print(e)
Explanation: Floating-point errors are rare in Python; this code demonstrates the typical use case.
7. AssertionError
Raised when an assert statement fails. Example:
try:
assert 1 == 2, "Assertion failed"
except AssertionError as e:
print(e)
Output
Assertion failed
Explanation: This code fails an assertion, raising an AssertionError
.
8. AttributeError
Raised when an attribute reference or assignment fails. Example:
class MyClass:
pass
obj = MyClass()
try:
obj.some_attribute
except AttributeError as e:
print(e)
Output
'MyClass' object has no attribute 'some_attribute'
Explanation: This code tries to access a non-existent attribute, causing an AttributeError
.
9. IndexError
Raised when a sequence subscript is out of range. Example:
my_list = [1, 2, 3]
try:
element = my_list[5]
except IndexError as e:
print(e)
Output
list index out of range
Explanation: This code tries to access an out-of-range index in a list, raising an IndexError
.
10. KeyError
Raised when a dictionary key is not found. Example:
d = {"key1": "value1"}
try:
val = d["key2"]
except KeyError as e:
print(e)
Output
'key2'
Explanation: This code attempts to access a non-existent dictionary key, causing a KeyError
.
11. MemoryError
Raised when an operation runs out of memory. Example:
try:
li = [1] * (10**10)
except MemoryError as e:
print(e)
Explanation: This code tries to create a very large list, causing a MemoryError
.
12. NameError
Raised when a local or global name is not found. Example:
try:
print(var)
except NameError as e:
print(e)
Output
name 'var' is not defined
Explanation: This code attempts to use an undefined variable, raising a NameError
.
13. OSError
Raised when a system-related operation (like file I/O) fails. Example:
try:
open("non_existent_file.txt")
except OSError as e:
print(e)
Output
[Errno 2] No such file or directory: 'non_existent_file.txt'
Explanation: This code tries to open a non-existent file, causing an OSError
.
14. TypeError
Raised when an operation or function is applied to an object of inappropriate type. Example:
try:
result = '2' + 2
except TypeError as e:
print(e)
Output
can only concatenate str (not "int") to str
Explanation: This code tries to add a string and an integer, causing a TypeError
.
15. ValueError
Raised when a function receives an argument of the right type but inappropriate value. Example:
try:
res = int("abc")
except ValueError as e:
print(e)
Output
invalid literal for int() with base 10: 'abc'
Explanation: This code tries to convert a non-numeric string to an integer, raising a ValueError
.
16. ImportError
Raised when an import statement has issues. Example:
try:
import mod
except ImportError as e:
print(e)
Output
No module named 'mod'
Explanation: This code attempts to import a non-existent module, causing an ImportError
.
17. ModuleNotFoundError
Raised when a module cannot be found. Example:
try:
import module
except ModuleNotFoundError as e:
print(e)
Output
No module named 'module'
Explanation: Similar to ImportError
, this code tries to import a module that doesn’t exist.
18. IOError
Raised when an I/O operation (like reading or writing to a file) fails. Example:
try:
open("non_existent_file.txt")
except IOError as e:
print(e)
Output
[Errno 2] No such file or directory: 'non_existent_file.txt'
Explanation: This is another example of file-related errors, causing an IOError
.
19. FileNotFoundError
Raised when a file or directory is requested but cannot be found. Example:
try:
open("non_existent_file.txt")
except FileNotFoundError as e:
print(e)
Output
[Errno 2] No such file or directory: 'non_existent_file.txt'
Explanation: This specifically catches the FileNotFoundError
when trying to open a missing file.
20. StopIteration
Raised when the next()
function is called and there are no more items in an iterator. Example:
my_iter = iter([1, 2, 3])
try:
while True:
print(next(my_iter))
except StopIteration as e:
print("End of iterator")
Output
1 2 3 End of iterator
Explanation: This code iterates through a list and raises StopIteration
when the list is exhausted.
21. KeyboardInterrupt
Raised when the user presses Ctrl+C or interrupts the program’s execution. Example:
try:
while True:
pass
except KeyboardInterrupt as e:
print("Program interrupted by user")
Explanation: This code runs an infinite loop until the user interrupts it with Ctrl+C.
22. SystemExit
Raised when the sys.exit()
function is called to exit the program. Example:
import sys
try:
sys.exit()
except SystemExit as e:
print("System exit called")
Output
System exit called
Explanation: This code calls sys.exit()
, raising a SystemExit
exception.
23. NotImplementedError
Raised when an abstract method that needs to be implemented is called. Example:
class BaseClass:
def some_method(self):
raise NotImplementedError("This method should be overridden")
try:
obj = BaseClass()
obj.some_method()
except NotImplementedError as e:
print(e)
Output
This method should be overridden
Explanation: This code demonstrates a base class method that should be overridden in subclasses, raising NotImplementedError
if called.
24. RuntimeError
Raised when a general error occurs in the program. Example:
try:
raise RuntimeError("A runtime error occurred")
except RuntimeError as e:
print(e)
Output
A runtime error occurred
Explanation: This manually raises a RuntimeError
and catches it.
25. RecursionError
Raised when the maximum recursion depth is exceeded. Example:
try:
def recursive_function():
recursive_function()
recursive_function()
except RecursionError as e:
print(e)
Output
maximum recursion depth exceeded
Explanation: This code defines a recursive function that calls itself indefinitely, causing a RecursionError
.
26. SyntaxError
Raised when there is an error in the syntax of the code. Example:
try:
eval('x === 2')
except SyntaxError as e:
print(e)
Output
invalid syntax (<string>, line 1)
Explanation: This code uses eval()
to evaluate an incorrect syntax, raising a SyntaxError
.
27. IndentationError
Raised when there is an indentation error in the code. Example:
try:
eval('def func():\n print("Hello")\n print("World")')
except IndentationError as e:
print(e)
Explanation: This code uses eval()
to evaluate code with incorrect indentation, causing an IndentationError
.
28. TabError
Raised when the indentation consists of inconsistent use of tabs and spaces. Example:
try:
eval('def func():\n\tprint("Hello")\n print("World")')
except TabError as e:
print(e)
Explanation: This code uses eval()
to evaluate code with mixed tabs and spaces, causing a TabError
.
29. UnicodeError
Raised when a Unicode-related encoding or decoding error occurs. Example:
try:
'æ'.encode('ascii')
except UnicodeError as e:
print(e)
Output
'ascii' codec can't encode character '\xe6' in position 0: ordinal not in range(128)
Explanation: This code tries to encode a non-ASCII character using the ASCII codec, raising a UnicodeError
.