Troubleshooting Common Exceptions
TypeError
A TypeError
exception is raised when an operation or function is applied to an object of an inappropriate type. This can happen when you try to perform an operation on incompatible data types, such as adding a string and an integer.
try:
result = "hello" + 42
except TypeError as e:
print(f"TypeError occurred: {e}")
ValueError
A ValueError
exception is raised when a function receives an argument of the correct type but an inappropriate value. This can happen when you try to convert a string to a number, but the string cannot be converted.
try:
result = int("abc")
except ValueError as e:
print(f"ValueError occurred: {e}")
IndexError
An IndexError
exception is raised when a sequence subscript (such as a list or tuple index) is out of range.
my_list = [1, 2, 3]
try:
print(my_list[3])
except IndexError as e:
print(f"IndexError occurred: {e}")
KeyError
A KeyError
exception is raised when a dictionary key is not found.
my_dict = {"a": 1, "b": 2}
try:
print(my_dict["c"])
except KeyError as e:
print(f"KeyError occurred: {e}")
ZeroDivisionError
A ZeroDivisionError
exception is raised when the second argument of a division or modulo operation is zero.
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"ZeroDivisionError occurred: {e}")
By understanding these common exceptions and how to handle them, you can write more robust and reliable Python code that can gracefully handle unexpected situations.