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.
Here’s a table listing all the major Python built-in exceptions along with a brief :
Exception Name DescriptionBaseException
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:
Python
try:
raise BaseException("This is a BaseException")
except BaseException as e:
print(e)
This is a BaseException
Explanation: This code manually raises a BaseException
and catches it, printing the exception message.
Exception
The base class for all non-exit exceptions. Example:
Python
try:
raise Exception("This is a generic exception")
except Exception as e:
print(e)
This is a generic exception
Explanation: This raises a generic Exception
and handles it, printing the message.
ArithmeticError
Base class for all errors related to arithmetic operations. Example:
Python
try:
raise ArithmeticError("Arithmetic error occurred")
except ArithmeticError as e:
print(e)
Arithmetic error occurred
Explanation: This raises an ArithmeticError
and catches it, displaying the error message.
ZeroDivisionError
Raised when a division or modulo operation is performed with zero as the divisor. Example:
Python
try:
result = 10 / 0
except ZeroDivisionError as e:
print(e)
Explanation: This code attempts to divide by zero, causing a ZeroDivisionError
.
OverflowError
Raised when a numerical operation exceeds the maximum limit of a data type. Example:
Python
import math
try:
result = math.exp(1000) # Exponential function with a large argument
except OverflowError as e:
print(e)
Explanation: The exponential function with a large argument causes an OverflowError
.
FloatingPointError
Raised when a floating-point operation fails. Example:
Python
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:
Python
try:
assert 1 == 2, "Assertion failed"
except AssertionError as e:
print(e)
Explanation: This code fails an assertion, raising an AssertionError
.
AttributeError
Raised when an attribute reference or assignment fails. Example:
Python
class MyClass:
pass
obj = MyClass()
try:
obj.some_attribute
except AttributeError as e:
print(e)
'MyClass' object has no attribute 'some_attribute'
Explanation: This code tries to access a non-existent attribute, causing an AttributeError
.
IndexError
Raised when a sequence subscript is out of range. Example:
Python
my_list = [1, 2, 3]
try:
element = my_list[5]
except IndexError as e:
print(e)
list index out of range
Explanation: This code tries to access an out-of-range index in a list, raising an IndexError
.
KeyError
Raised when a dictionary key is not found. Example:
Python
d = {"key1": "value1"}
try:
val = d["key2"]
except KeyError as e:
print(e)
Explanation: This code attempts to access a non-existent dictionary key, causing a KeyError
.
MemoryError
Raised when an operation runs out of memory. Example:
Python
try:
li = [1] * (10**10)
except MemoryError as e:
print(e)
Explanation: This code tries to create a very large list, causing a MemoryError
.
NameError
Raised when a local or global name is not found. Example:
Python
try:
print(var)
except NameError as e:
print(e)
name 'var' is not defined
Explanation: This code attempts to use an undefined variable, raising a NameError
.
OSError
Raised when a system-related operation (like file I/O) fails. Example:
Python
try:
open("non_existent_file.txt")
except OSError as e:
print(e)
[Errno 2] No such file or directory: 'non_existent_file.txt'
Explanation: This code tries to open a non-existent file, causing an OSError
.
TypeError
Raised when an operation or function is applied to an object of inappropriate type. Example:
Python
try:
result = '2' + 2
except TypeError as e:
print(e)
can only concatenate str (not "int") to str
Explanation: This code tries to add a string and an integer, causing a TypeError
.
ValueError
Raised when a function receives an argument of the right type but inappropriate value. Example:
Python
try:
res = int("abc")
except ValueError as e:
print(e)
invalid literal for int() with base 10: 'abc'
Explanation: This code tries to convert a non-numeric string to an integer, raising a ValueError
.
ImportError
Raised when an import statement has issues. Example:
Python
try:
import mod
except ImportError as e:
print(e)
No module named 'mod'
Explanation: This code attempts to import a non-existent module, causing an ImportError
.
ModuleNotFoundError
Raised when a module cannot be found. Example:
Python
try:
import module
except ModuleNotFoundError as e:
print(e)
No module named 'module'
Explanation: Similar to ImportError
, this code tries to import a module that doesn't exist.
IOError
Raised when an I/O operation (like reading or writing to a file) fails. Example:
Python
try:
open("non_existent_file.txt")
except IOError as e:
print(e)
[Errno 2] No such file or directory: 'non_existent_file.txt'
Explanation: This is another example of file-related errors, causing an IOError
.
FileNotFoundError
Raised when a file or directory is requested but cannot be found. Example:
Python
try:
open("non_existent_file.txt")
except FileNotFoundError as e:
print(e)
[Errno 2] No such file or directory: 'non_existent_file.txt'
Explanation: This specifically catches the FileNotFoundError
when trying to open a missing file.
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")
1 2 3 End of iterator
Explanation: This code iterates through a list and raises StopIteration
when the list is exhausted.
KeyboardInterrupt
Raised when the user presses Ctrl+C or interrupts the program’s execution. Example:
Python
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")
System exit called
Explanation: This code calls sys.exit()
, raising a SystemExit
exception.
NotImplementedError
Raised when an abstract method that needs to be implemented is called. Example:
Python
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)
This method should be overridden
Explanation: This code demonstrates a base class method that should be overridden in subclasses, raising NotImplementedError
if called.
RuntimeError
Raised when a general error occurs in the program. Example:
Python
try:
raise RuntimeError("A runtime error occurred")
except RuntimeError as e:
print(e)
A runtime error occurred
Explanation: This manually raises a RuntimeError
and catches it.
RecursionError
Raised when the maximum recursion depth is exceeded. Example:
Python
try:
def recursive_function():
recursive_function()
recursive_function()
except RecursionError as e:
print(e)
maximum recursion depth exceeded
Explanation: This code defines a recursive function that calls itself indefinitely, causing a RecursionError
.
SyntaxError
Raised when there is an error in the syntax of the code. Example:
Python
try:
eval('x === 2')
except SyntaxError as e:
print(e)
invalid syntax (<string>, line 1)
Explanation: This code uses eval()
to evaluate an incorrect syntax, raising a SyntaxError
.
IndentationError
Raised when there is an indentation error in the code. Example:
Python
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
.
TabError
Raised when the indentation consists of inconsistent use of tabs and spaces. Example:
Python
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
.
UnicodeError
Raised when a Unicode-related encoding or decoding error occurs. Example:
Python
try:
'æ'.encode('ascii')
except UnicodeError as e:
print(e)
'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
.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4