KEMBAR78
Exception Handling Practice Codes | PDF
0% found this document useful (0 votes)
3 views2 pages

Exception Handling Practice Codes

Uploaded by

riyarana4908
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)
3 views2 pages

Exception Handling Practice Codes

Uploaded by

riyarana4908
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/ 2

Python Exception Handling Practice Codes

1. Division by Zero
try:
num1 = int(input("Enter numerator: "))
num2 = int(input("Enter denominator: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Please enter valid integers.")

2. Index Error
try:
colors = ['red', 'blue', 'green']
index = int(input("Enter index (0 to 2): "))
print("Selected color:", colors[index])
except IndexError:
print("Error: Index out of range.")
except ValueError:
print("Error: Enter a valid integer.")

3. File Not Found


try:
file_name = input("Enter filename to read: ")
with open(file_name, 'r') as f:
print(f.read())
except FileNotFoundError:
print("Error: File not found.")

4. Type Error
try:
num = input("Enter a number: ")
result = num + 5
print(result)
except TypeError:
print("Error: You can't add a string and an integer.")

5. ValueError in math module


import math

try:
# sqrt() expects 1 argument, passing 2 will cause error
result = math.sqrt(16, 25)
except TypeError as e:
print("Caught an error:", e)
Python Exception Handling Practice Codes

6. Multiple Exceptions
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
print("Quotient:", a / b)
except (ZeroDivisionError, ValueError) as e:
print("Error occurred:", e)

7. Custom Exception
class NegativeNumberError(Exception):
pass

try:
num = int(input("Enter a positive number: "))
if num < 0:
raise NegativeNumberError("Negative number is not allowed.")
print("You entered:", num)
except NegativeNumberError as e:
print("Caught custom exception:", e)

You might also like