SyntaxError
IndentationError
NameError
TypeError
ValueError
ZeroDivisionError
IndexError
KeyError
FileNotFoundError
AttributeError
PermissionError
FileExistsError
OSError
EOFError
ArithmeticError
FloatingPointError
ImportError
ModuleNotFoundError
MemoryError
RecursionError
GeneratorExit
SystemExit
KeyboardInterrupt
StopIteration
Exception handling in Python is essential for gracefully dealing with errors and exceptions that can occur during program execution. Here are 30 different types of exceptions in Python, along with examples of how to handle them:
SyntaxError:
Explanation: Raised when there's a syntax error in the code.
Example:
def my_function()
pass # Missing colon, raises SyntaxError
IndentationError:
Explanation: Occurs when there's an indentation-related error.
Example:
if True:
print("Indented incorrectly") # Raises IndentationError
NameError:
Explanation: Raised when a variable or name is not found in the current scope.
Example:
print(undefined_variable) # Raises NameError
TypeError:
Explanation: Occurs when an operation is performed on an inappropriate data type.
Example:
result = "5" + 5 # Raises TypeError
ValueError:
Explanation: Raised when a built-in operation or function receives an argument of the correct type but with an inappropriate value.
Example:
num = int("abc") # Raises ValueError
ZeroDivisionError:
Explanation: Occurs when attempting to divide by zero.
Example:
result = 1 / 0 # Raises ZeroDivisionError
IndexError:
Explanation: Raised when trying to access an element of a list or sequence using an index that is out of bounds.
Example:
my_list = [1, 2, 3]
element = my_list[5] # Raises IndexError
KeyError:
Explanation: Occurs when trying to access a dictionary key that does not exist.
Example:
my_dict = {"key1": "value1"}
value = my_dict["key2"] # Raises KeyError
FileNotFoundError:
Explanation: Raised when trying to open a file that does not exist.
Example:
with open("nonexistent.txt", "r") as file:
content = file.read() # Raises FileNotFoundError
AttributeError:
Explanation: Occurs when trying to access an attribute or method that does not exist on an object.
Example:
class MyClass:
def __init__(self):
self.value = 42
obj = MyClass()
result = obj.nonexistent_method() # Raises AttributeError
PermissionError:
Explanation: Raised when an operation that requires special permissions is denied.
Example:
with open("/root/sensitive.txt", "w") as file:
file.write("This requires special permissions") # Raises PermissionError
FileExistsError:
Explanation: Occurs when trying to create a f*ile or directory that already exists*.
Example:
import os
os.mkdir("my_directory")
os.mkdir("my_directory") # Raises FileExistsError
OSError:
Explanation: A general exception for I/O-related errors.
Example:
try:
file = open("/root/sensitive.txt", "r")
except OSError as e:
print(f"OSError: {e}")
EOFError:
Explanation: Raised when there is no input to read from a file or the user cancels the input operation.
Example:
try:
user_input = input("Enter something: ")
print(f"You entered: {user_input}")
except EOFError:
print("No input provided")
ArithmeticError:
Explanation: A base class for arithmetic errors.
Example:
try:
result = 1 / 0 # Raises ZeroDivisionError (subclass of ArithmeticError)
except ArithmeticError as e:
print(f"ArithmeticError: {e}")
FloatingPointError:
Explanation: Raised when a floating-point operation fails.
Example:
try:
result = 1.0 / 0.0 # Raises FloatingPointError
except FloatingPointError as e:
print(f"FloatingPointError: {e}")
ImportError:
Explanation: Occurs when an imported module is not found.
Example:
try:
import non_existent_module # Raises ImportError
except ImportError as e:
print(f"ImportError: {e}")
ModuleNotFoundError:
Explanation: Raised when an imported module is not found (Python 3.6+).
Example:
try:
import non_existent_module # Raises ModuleNotFoundError
except ModuleNotFoundError as e:
print(f"ModuleNotFoundError: {e}")
MemoryError:
Explanation: Occurs when there's not enough memory available.
Example:
try:
big_list = [0] * 1000000000 # Raises MemoryError
except MemoryError as e:
print(f"MemoryError: {e}")
RecursionError:
Explanation: Raised when the maximum recursion depth is exceeded.
Example:
def recursive_function(n):
return recursive_function(n - 1) # Raises RecursionError when n is too large
GeneratorExit:
Explanation: Raised when a generator's close() method is called.
Example:
def my_generator():
try:
yield 1
yield 2
except GeneratorExit:
print("Generator closed")
gen = my_generator()
next(gen)
gen.close() # Raises GeneratorExit
SystemExit:
Explanation: Raised when the sys.exit() function is called to exit the program.
Example:
import sys
try:
sys.exit(1)
except SystemExit as e:
print(f"SystemExit: {e}
")
KeyboardInterrupt:
Explanation: Raised when the user interrupts the program (e.g., by pressing Ctrl+C).
Example:
try:
while True:
pass # Infinite loop
except KeyboardInterrupt:
print("Program interrupted by the user")
StopIteration:
Explanation: Raised when there are no more items to be returned by an iterator.
Example:
my_iterator = iter([1, 2, 3])
Top comments (0)