Challenges-18
Challenges-18
Write a function safe_divide(a, b) that divides a by b, but catches ZeroDivisionError and prints an
appropriate message.
safe_divide(1, 0)
ZeroDivisionError
Write a function get_integer() that asks the user for an integer input. If the user enters a non-integer value,
catch the ValueError and prompt them again.
def get_integer(n):
try:
if n == int(n):
print("The number is an integer")
except ValueError:
print("Its a ValueError")
get_integer("hello")
Its a ValueError
Write a function safe_list_access(lst, index) that tries to access an element from lst. Handle IndexError (if
index is out of range) and TypeError (if index is not an integer).
'IndexError'
4. File Handling with Error Handling
Write a function read_file(filename) that tries to read a file and prints its contents. Handle
FileNotFoundError if the file does not exist.
def read_file(filename):
try:
with open(filename, "r") as file:
return file.read()
except FileNotFoundError:
return "FileNotFoundError"
read_file("hello.txt")
'FileNotFoundError'
Write a function get_value(dictionary, key) that tries to return dictionary[key]. If the key is missing, handle
the KeyError and return "Key not found" instead.
Write a function calculate_square_root() that asks for a number and returns its square root. Handle
ValueError if the user enters a negative number or non- numeric input.
import math
def calculate_square_root(n):
try:
if n < 0:
return math.sqrt(n)
except ValueError:
return "ValueError"
except TypeError:
return "TypeError"
calculate_square_root(-34)
'ValueError'
Write a function write_to_file(filename, text) that writes text to filename. Use a try-except-finally block to
ensure the file closes properly, even if an error occurs.
def write_to_file(filename, text):
try:
with open(filename, "w") as file:
file.write(text)
except Exception as e:
print(f"An error occurred: {e}")
finally:
print("The file has been closed.")
write_to_file("hello.txt", "Hello World")
Write a function validate_age(age) that raises a custom exception (ValueError) if the age is below 18.
def validate_age(age):
try:
if age < 18:
raise ValueError("Age is below 18")
except ValueError as e:
print(e)
validate_age(16)
Age is below 18
1.0
'ZeroDivisionError'