About Lesson
Write a Program to Handle Division by Zero
- Objective: Write a Python program that handles division by zero using exception handling.
- Steps:
- Prompt the user to enter two numbers.
- Perform division and handle
ZeroDivisionError
. - Print the result or an error message.
python
try: numerator = float(input("Enter the numerator: ")) denominator = float(input("Enter the denominator: ")) result = numerator / denominator print(f"The result is {result}") except ZeroDivisionError: print("Error: Cannot divide by zero")
Create Custom Exceptions for a Specific Scenario
- Objective: Create custom exceptions to handle specific scenarios, such as invalid input.
- Steps:
- Define a custom exception class.
- Write a function that raises the custom exception for invalid input.
- Use a
try-except
block to handle the custom exception.
python
class InvalidInputError(Exception): pass def validate_input(value): if not isinstance(value, int): raise InvalidInputError("Input must be an integer") try: user_input = input("Enter an integer: ") validate_input(int(user_input)) print("Valid input") except InvalidInputError as e: print(e) # Output: Input must be an integer except ValueError: print("Error: Input must be an integer")