errorswithexception
errorswithexception
Solution:
try:
num = int('abc')
except ValueError:
print("Invalid integer value")
Problem Statement 2:
Catching a KeyError when accessing a dictionary with a non-existent key.
Solution:
Problem Statement 3:
Catching an IndexError when accessing an element beyond the length of a list.
Solution:
my_list = [1, 2, 3]
try:
item = my_list[5]
except IndexError:
print("List index out of range")
Problem Statement 4:
Catching an AttributeError when accessing a non-existent attribute of an object.
Solution:
class MyClass:
pass
obj = MyClass()
try:
obj.nonexistent_attribute
except AttributeError:
print("Attribute does not exist")
Problem Statement 5:
Catching a ZeroDivisionError when dividing by zero.
Solution:
try:
result = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Problem Statement 6:
Catching a TypeError when performing an invalid operation, such as adding a string
to an integer.
Solution:
try:
result = 'hello' + 5
except TypeError:
print("Invalid operation")
Problem Statement 7:
Catching a NameError when referencing an undefined variable.
Solution:
try:
undefined_variable += 1
except NameError:
print("Variable is not defined")
Problem Statement 8:
Catching an IOError when trying to read a file that doesn't exist.
Solution:
try:
with open('nonexistent_file.txt', 'r') as f:
content = f.read()
except IOError:
print("File not found")
Problem Statement 9:
Catching a ImportError when trying to import a module that doesn't exist.
Solution:
try:
import nonexistent_module
except ImportError:
print("Module not found")
Solution:
class CustomException(Exception):
pass
try:
if False:
raise CustomException("A custom condition was not met")
except CustomException as e:
print(str(e))