0% found this document useful (0 votes)
4 views

Challenges-18

The document outlines a series of Python functions that demonstrate error handling using try-except blocks. It covers various exceptions such as ZeroDivisionError, ValueError, IndexError, and KeyError, providing examples for each scenario. Additionally, it includes techniques for handling user input, file operations, and custom exceptions.

Uploaded by

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

Challenges-18

The document outlines a series of Python functions that demonstrate error handling using try-except blocks. It covers various exceptions such as ZeroDivisionError, ValueError, IndexError, and KeyError, providing examples for each scenario. Additionally, it includes techniques for handling user input, file operations, and custom exceptions.

Uploaded by

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

keyboard_arrow_down Day 18 Challenge – Mastering try-except in python

1. Handling Division by Zero

Write a function safe_divide(a, b) that divides a by b, but catches ZeroDivisionError and prints an
appropriate message.

def safe_divide(a, b):


try:
if b == 0:
print("ZeroDivisionError")
except:
print("Something else went wrong")

safe_divide(1, 0)

ZeroDivisionError

2. Handling Invalid Input

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

3. Handling Multiple Exceptions

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

def safe_list_access(lst, index):


try:
return lst[index]
except IndexError:
return "IndexError"
except TypeError:
return "TypeError"
safe_list_access([1, 2, 3], 4)

'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'

5. Handling KeyError in Dictionary Lookup

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.

def get_value(dictionary, key):


try:
return dictionary[key]
except KeyError:
return "Key not found"
get_value({"Tech": "Club"}, "world")

'Key not found'

6. Exception Handling in User Input

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'

7. Using finally in Exception Handling

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

The file has been closed.

8. Raising Custom Exceptions

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

9. Nested try-except Blocks

Write a function nested_exception_handling(a, b, lst, index) that:

1. Tries to divide a by b (handle ZeroDivisionError).


2. Tries to access lst[index] (handle IndexError).
3. Uses a nested try-except block for handling errors separately.

def nested_exception_handling(a, b, lst, index):


try:
result = a / b
print(result)
try:
return lst[index]
except IndexError:
return "IndexError"
except ZeroDivisionError:
return "ZeroDivisionError"

nested_exception_handling(1, 1, [1, 2, 3], 2)


nested_exception_handling(1, 0, [1, 2, 3], 4)

1.0
'ZeroDivisionError'

Start coding or generate with AI.

You might also like