Statement of Completion#e340d417
Python Basics
medium
Error Handling Practice
Resolution
Activities
Activities¶
Activity 1. Handling ZeroDivisionError¶
In [4]:
# write your code here
def safe_division(a, b):
try:
return a / b
except ZeroDivisionError:
return "Cannot divide by zero!"
safe_division(10, 0)
Out[4]:
'Cannot divide by zero!'
Activity 2. Handling ValueError in Input Conversion¶
In [7]:
# Write your code here
def convert_to_int(string):
try:
return int(string)
except ValueError:
return "Invalid input!"
convert_to_int('a')
Out[7]:
'Invalid input!'
Activity 3. Handling Multiple Exceptions¶
In [13]:
# write your code here
def safe_input_division(a, b):
try:
return int(a) / int(b)
except ValueError:
return "Invalid input!"
except ZeroDivisionError:
return "Cannot divide by zero!"
In [14]:
# test case 1
safe_input_division("10", 10.5)
Out[14]:
1.0
In [15]:
# test case 2
safe_input_division("hello", 2.0)
Out[15]:
'Invalid input!'
In [16]:
# test case 3
safe_input_division("10", 0.0)
Out[16]:
'Cannot divide by zero!'
Activity 4. Raising ValueError¶
In [22]:
# write your code here
def check_positive(a):
if a < 0:
raise ValueError("Negative numbers are not allowed")
return "Valid number"
check_positive(-1)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[22], line 8 4 raise ValueError("Negative numbers are not allowed") 5 return "Valid number" ----> 8 check_positive(-1) Cell In[22], line 4, in check_positive(a) 2 def check_positive(a): 3 if a < 0: ----> 4 raise ValueError("Negative numbers are not allowed") 5 return "Valid number" ValueError: Negative numbers are not allowed
Activity 5. Invalid Age Input¶
In [33]:
# write your code here
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return "Age is valid"
check_age(-1)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[33], line 8 4 raise ValueError("Age cannot be negative") 5 return "Age is valid" ----> 8 check_age(-1) Cell In[33], line 4, in check_age(age) 2 def check_age(age): 3 if age < 0: ----> 4 raise ValueError("Age cannot be negative") 5 return "Age is valid" ValueError: Age cannot be negative
Activity 6. Catching TypeError¶
In [31]:
# write your code here
def safe_addition(a, b):
try:
return a + b
except TypeError:
return "Type mismatch!"
safe_addition("3", 4)
Out[31]:
'Type mismatch!'
In [ ]:
# test case 1
safe_addition(5, 6.0)
In [ ]:
# test case 2
safe_addition("hello", 2)
Activity 7. Handling AttributeError¶
In [39]:
# write your code here
def call_invalid_method(value):
try:
value.invalid_method()
except AttributeError:
return "Invalid operation!"
In [40]:
call_invalid_method(2)
Out[40]:
'Invalid operation!'
Activity 8. Invalid Email Format¶
In [88]:
# write your code here
def validate_email(email):
if email.count("@") != 1:
raise ValueError("Invalid email format")
return "Email is valid"
validate_email("aa@b@bb")
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[88], line 7 4 raise ValueError("Invalid email format") 5 return "Email is valid" ----> 7 validate_email("aa@b@bb") Cell In[88], line 4, in validate_email(email) 2 def validate_email(email): 3 if email.count("@") != 1: ----> 4 raise ValueError("Invalid email format") 5 return "Email is valid" ValueError: Invalid email format
Activity 9. Using finally block to Ensure Cleanup¶
In [47]:
# write your code here
def cleanup_example():
try:
var = "In use"
raise ValueError("Some error")
finally:
var = "Cleaned"
return var
cleanup_example()
Out[47]:
'Cleaned'
Activity 10. Nested Try-Except Blocks¶
In [55]:
# complete the given code
def nested_error_handling(string):
try:
try:
return int(string)
except ValueError:
raise TypeError("Inner Type Error")
except TypeError:
return "Handled in outer block"
nested_error_handling("a")
Out[55]:
'Handled in outer block'
Activity 11. Handle Empty String¶
In [58]:
# write your code here
def check_empty_string(s):
if not s:
raise ValueError("String cannot be empty!")
return "String is valid"
check_empty_string("")
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[58], line 8 5 raise ValueError("String cannot be empty!") 6 return "String is valid" ----> 8 check_empty_string("") Cell In[58], line 5, in check_empty_string(s) 3 def check_empty_string(s): 4 if not s: ----> 5 raise ValueError("String cannot be empty!") 6 return "String is valid" ValueError: String cannot be empty!
Activity 12. Combining Try-Except-Else-Finally¶
In [63]:
# write your code here
def complete_error_handling(a, b):
try:
result = a / b
except ZeroDivisionError:
return "Cannot divide by zero!"
else:
return result
finally:
print("Operation completed!")
complete_error_handling(3, 0)
Operation completed!
Out[63]:
'Cannot divide by zero!'
Activity 13. Custom Exception for Invalid Password Length¶
In [73]:
class InvalidPasswordError(Exception):
pass
def validate_password(password):
# write your code here
if len(password) < 8:
raise InvalidPasswordError("Password must be at least 8 characters long!")
return "Password is valid"
In [74]:
validate_password("abcdefghjk")
Out[74]:
'Password is valid'
Activity 14. Substring Not Found¶
In [80]:
# write your code here
def find_substring(s, sub):
try:
index = s.index(sub)
return f"Substring found at index {index}"
except ValueError:
return "Substring not found!"
find_substring("check boolean input", "input")
Out[80]:
'Substring found at index 14'
Activity 15. Check Boolean Input Validation¶
In [82]:
# write your code here
def validate_boolean(b):
if not isinstance(b, bool):
raise TypeError("Value must be a boolean!")
return "Boolean is valid"
validate_boolean(33)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[82], line 7 4 raise TypeError("Value must be a boolean!") 5 return "Boolean is valid" ----> 7 validate_boolean(33) Cell In[82], line 4, in validate_boolean(b) 2 def validate_boolean(b): 3 if not isinstance(b, bool): ----> 4 raise TypeError("Value must be a boolean!") 5 return "Boolean is valid" TypeError: Value must be a boolean!
Activity 16. Using else with Try Block¶
In [86]:
# write your code here
def divide_numbers(a, b):
try:
c = a / b
except ZeroDivisionError:
return "Cannot divide by zero!"
else:
return c
divide_numbers(3, 0)
Out[86]:
'Cannot divide by zero!'
In [ ]: