Statement of Completion#ae7939c2
Python Basics
medium
Error Handling Practice
Resolution
Activities
Project.ipynb
Activities¶
Activity 1. Handling ZeroDivisionError¶
In [3]:
def safe_division(a, b):
try:
return a / b
except ZeroDivisionError:
return("Cannot divide by zero!")
safe_division(3, 0)
Out[3]:
'Cannot divide by zero!'
Activity 2. Handling ValueError in Input Conversion¶
In [7]:
def convert_to_int(string):
try:
return int(string)
except ValueError:
return "Invalid input!"
convert_to_int('2')
Out[7]:
2
Activity 3. Handling Multiple Exceptions¶
In [17]:
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 [18]:
# test case 1
safe_input_division("10", 10.5)
Out[18]:
1.0
In [19]:
# test case 2
safe_input_division("hello", 2.0)
Out[19]:
'Invalid input!'
In [20]:
# test case 3
safe_input_division("10", 0.0)
Out[20]:
'Cannot divide by zero!'
Activity 4. Raising ValueError¶
In [27]:
def check_positive(num):
if num < 0:
raise ValueError("Negative numbers are not allowed")
return "Valid number"
Activity 5. Invalid Age Input¶
In [36]:
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return "Age is valid"
check_age(-12)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[36], line 6 3 raise ValueError("Age cannot be negative") 4 return "Age is valid" ----> 6 check_age(-12) Cell In[36], line 3, in check_age(age) 1 def check_age(age): 2 if age < 0: ----> 3 raise ValueError("Age cannot be negative") 4 return "Age is valid" ValueError: Age cannot be negative
Activity 6. Catching TypeError¶
In [45]:
def safe_addition(a, b):
try:
return a + b
except TypeError:
return "Type mismatch!"
In [46]:
# test case 1
safe_addition(5, 6.0)
Out[46]:
11.0
In [47]:
# test case 2
safe_addition("hello", 2)
Out[47]:
'Type mismatch!'
Activity 7. Handling AttributeError¶
In [52]:
def call_invalid_method(value):
try:
return invalid_method(value)
except NameError:
return "Invalid operation!"
call_invalid_method(10)
Out[52]:
'Invalid operation!'
Activity 8. Invalid Email Format¶
In [55]:
def validate_email(email):
if '@' not in email:
raise ValueError("Invalid email format")
return "Email is valid"
validate_email('cunninghambprotonmail.com')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[55], line 6 3 raise ValueError("Invalid email format") 4 return "Email is valid" ----> 6 validate_email('cunninghambprotonmail.com') Cell In[55], line 3, in validate_email(email) 1 def validate_email(email): 2 if '@' not in email: ----> 3 raise ValueError("Invalid email format") 4 return "Email is valid" ValueError: Invalid email format
Activity 9. Using finally block to Ensure Cleanup¶
In [67]:
def cleanup_example():
var = "In use"
try:
raise Exception("Some error")
finally:
var = "Cleaned"
return var
cleanup_example()
Out[67]:
'Cleaned'
Activity 10. Nested Try-Except Blocks¶
In [68]:
def nested_error_handling(value):
try:
try:
return int(value)
except ValueError:
raise TypeError("Inner Type Error")
except TypeError:
return "Handled in outer block"
Activity 11. Handle Empty String¶
In [71]:
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[71], line 6 3 raise ValueError("String cannot be empty!") 4 return "String is valid" ----> 6 check_empty_string("") Cell In[71], line 3, in check_empty_string(s) 1 def check_empty_string(s): 2 if not s: ----> 3 raise ValueError("String cannot be empty!") 4 return "String is valid" ValueError: String cannot be empty!
Activity 12. Combining Try-Except-Else-Finally¶
In [74]:
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(2, 0)
Operation completed!
Out[74]:
'Cannot divide by zero!'
Activity 13. Custom Exception for Invalid Password Length¶
In [78]:
class InvalidPasswordError(Exception):
pass
def validate_password(password):
if len(password) < 8:
raise InvalidPasswordError("Password must be at least 8 characters long!")
return "Password is valid"
validate_password('1245678')
--------------------------------------------------------------------------- InvalidPasswordError Traceback (most recent call last) Cell In[78], line 9 6 raise InvalidPasswordError("Password must be at least 8 characters long!") 7 return "Password is valid" ----> 9 validate_password('1245678') Cell In[78], line 6, in validate_password(password) 4 def validate_password(password): 5 if len(password) < 8: ----> 6 raise InvalidPasswordError("Password must be at least 8 characters long!") 7 return "Password is valid" InvalidPasswordError: Password must be at least 8 characters long!
Activity 14. Substring Not Found¶
In [83]:
def find_substring(string, substring):
try:
index = string.index(substring)
return f"Substring found at index {index}"
except ValueError:
return "Substring not found!"
Activity 15. Check Boolean Input Validation¶
In [87]:
def validate_boolean(b):
if type(b) != bool:
raise TypeError("Value must be a boolean!")
return "Boolean is valid"
validate_boolean('True')
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[87], line 6 3 raise TypeError("Value must be a boolean!") 4 return "Boolean is valid" ----> 6 validate_boolean('True') Cell In[87], line 3, in validate_boolean(b) 1 def validate_boolean(b): 2 if type(b) != bool: ----> 3 raise TypeError("Value must be a boolean!") 4 return "Boolean is valid" TypeError: Value must be a boolean!
Activity 16. Using else with Try Block¶
In [89]:
def divide_numbers(a, b):
try:
a / b
except ZeroDivisionError:
return "Cannot divide by zero!"
else:
return a / b
In [ ]: