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

Basic Exception Handling

Uploaded by

somak.lahiri1d
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Basic Exception Handling

Uploaded by

somak.lahiri1d
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Basic Exception Handling

● Problem: Write a Python program that takes an integer input from the user and prints its

reciprocal. Use exception handling to catch a ZeroDivisionError and print an appropriate

message if the user tries to enter zero.

2. File Handling Error

● Problem: Write a Python program to open a file named user_data.txt and read its

contents. Use exception handling to manage a FileNotFoundError if the file does not exist

and print a custom error message.

3. Custom Exception

● Problem: Define a custom exception called NegativeNumberError. Write a Python program

that asks the user for a number and raises this exception if the number is negative,

catching the exception and displaying an appropriate message.

4. Multiple Exceptions

● Problem: Write a Python program that asks the user to input a number and calculates the

square root of the number. Your program should handle exceptions for at least two types

of errors: ValueError for non-numeric inputs and TypeError if a wrong data type is passed

somehow, despite the input.

5. Using finally

● Problem: Write a Python program that attempts to write data to a file and uses a finally

block to ensure that the file stream is closed, regardless of whether an exception occurs.

6. Nested Exception Handling

● Problem: Create a Python program with nested try statements: the outer block should

handle file operations, and the inner block should handle arithmetic operations. Use the

except blocks appropriately to catch and print specific error messages.

7. Raising an Exception with assert

● Problem: Write a Python function that takes two integers and divides them. Use the assert

statement to ensure that the denominator is not zero before performing the division. Raise

an AssertionError with an appropriate message if the condition fails.

8. Handling Multiple Specific Exceptions

● Problem: Write a Python program that prompts the user to enter an integer and then tries

to convert this input into an integer. Catch specific exceptions like ValueError if the input is
not an integer and a general exception to catch other unforeseen errors.

9. Custom Handling for Common Errors

● Problem: Develop a Python program that accepts a list of numbers from the user and

prints the reciprocal of each. Use exception handling to specifically catch and handle the

cases of TypeError (if the user enters non-numeric types) and ZeroDivisionError (if the user

enters zero).

1. try:

number = int(input("Enter an integer: "))

reciprocal = 1 / number

print(f"The reciprocal of {number} is {reciprocal}")

except ZeroDivisionError:

print("Error: Cannot divide by zero.")

except ValueError:

print("Error: Invalid input, please enter an integer.")

OUTPUT
Enter an integer: 5

The reciprocal of 5 is 0.2

Enter an integer: 0

Error: Cannot divide by zero.

2. try:

with open("user_data.txt", "r") as file:

data = file.read()

print("File contents:")

print(data)

except FileNotFoundError:

print("Error: File 'user_data.txt' not found.")


OUTPUT

Assuming user_data.txt does not exist:

Error: The file 'user_data.txt' was not found.

If the file exists with content "Hello, World!":

File contents:

Hello, World!

3. class NegativeNumberError(Exception):

"""Custom exception for handling negative numbers."""

pass

try:

number = int(input("Enter a number: "))

if number < 0:

raise NegativeNumberError("Negative numbers are not allowed.")

print(f"You entered: {number}")

except NegativeNumberError as e:

print(f"Error: {e}")

except ValueError:

print("Error: Invalid input, please enter a number.")

OUTPUT

Enter a positive number: -3

Negative numbers are not allowed.

Enter a positive number: 10

You entered 10

4. import math

try:

number = float(input("Enter a number: "))


square_root = math.sqrt(number)

print(f"The square root of {number} is {square_root}")

except ValueError:

print("Error: Please enter a numeric value.")

except TypeError:

print("Error: Incorrect data type encountered.")

OUTPUT

Enter a number to find its square root: 16

The square root of 16.0 is 4.0

Enter a number to find its square root: abc

Error: Please enter a numeric value.

5. try:

file = open("output.txt", "w")

file.write("This is a test line.")

print("Data written to file successfully.")

except IOError:

print("Error: Unable to write to file.")

finally:

file.close()

print("File closed.")

OUTPUT

Data written to file.

File closed.

6. try:

file = open("data.txt", "r")

try:

number = int(file.readline())

result = 10 / number
print(f"Result of division: {result}")

except ZeroDivisionError:

print("Error: Division by zero is not allowed.")

except ValueError:

print("Error: Could not convert data to an integer.")

finally:

file.close()

print("Inner file handling block complete.")

except FileNotFoundError:

print("Error: The file 'data.txt' was not found.")

OUTPUT

Assuming numbers.txt does not exist:

Error: The file 'numbers.txt' was not found.

If numbers.txt contains 10 and 0:

Error: Division by zero.

If numbers.txt contains 10 and two:

Error: Invalid number format.

7. try:

file = open("data.txt", "r")

try:

number = int(file.readline())

result = 10 / number

print(f"Result of division: {result}")

except ZeroDivisionError:

print("Error: Division by zero is not allowed.")

except ValueError:

print("Error: Could not convert data to an integer.")


finally:

file.close()

print("Inner file handling block complete.")

except FileNotFoundError:

print("Error: The file 'data.txt' was not found.")

OUTPUT

Enter numerator: 10

Enter denominator: 2

Result: 5.0

Enter numerator: 10

Enter denominator: 0

Error: Denominator cannot be zero.

8. try:

number = int(input("Enter an integer: "))

print(f"You entered {number}")

except ValueError:

print("Error: That's not a valid integer.")

except Exception as e:

print("An unexpected error occurred:", e)

Enter an integer: 42

You entered 42

OUTPUT

Enter an integer: hello

Error: That's not a valid integer.

9. try:
numbers = input("Enter numbers separated by spaces: ").split()

for num in numbers:

try:

reciprocal = 1 / float(num)

print(f"The reciprocal of {num} is {reciprocal}")

except ZeroDivisionError:

print(f"Error: Cannot take reciprocal of zero ({num}).")

except ValueError:

print(f"Error: '{num}' is not a number.")

except Exception as e:

print("An unexpected error occurred:", e)

OUTPUT

Enter numbers separated by spaces: 4 5 0 abc

The reciprocal of 4 is 0.25

The reciprocal of 5 is 0.2

Error: Cannot take reciprocal of zero (0).

Error: 'abc' is not a number.

You might also like