0% found this document useful (0 votes)
783 views2 pages

errorswithexception

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
783 views2 pages

errorswithexception

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

Problem Statement 1:

Catching a ValueError when attempting to parse an invalid integer.

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:

my_dict = {'key': 'value'}


try:
value = my_dict['non_existent_key']
except KeyError:
print("Key not found in dictionary")

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")

Problem Statement 10:


Catching a custom exception when a specific condition is not met.

Solution:

class CustomException(Exception):
pass

try:
if False:
raise CustomException("A custom condition was not met")
except CustomException as e:
print(str(e))

You might also like