0% found this document useful (0 votes)
6 views2 pages

Exception Handling

Uploaded by

goraipriyam
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)
6 views2 pages

Exception Handling

Uploaded by

goraipriyam
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

Exception Handling

1. Write a program that reads two numbers from user input, divides the first by the
second, and handles division by zero and invalid input errors using try-except blocks.
2. Write a code snippet that tries to open a file and reads an integer from user input,
catching and printing a helpful message for:
- FileNotFoundError
- ValueError
- ZeroDivisionError
3. Modify the division program so that if no exceptions occur, it prints "Operation
successful" using else, and always prints "Program ended" using finally.
4. Define a custom exception called NegativeNumberError. Write a function that raises
this exception if the input number is negative. Handle this exception when calling the
function.
5. Given a list with integers and strings, write code to try converting each element to an
integer and handle ValueError and TypeError in a single except block.
6. Implement a function that accepts age as input. Raise a ValueError if age is negative
and handle this exception in your main code.
7. Write a program that keeps asking for a valid integer input until the user provides
one, handling invalid input with exception handling and printing a message each time
there's an error.
8. Write a function that opens a file, reads content, and handles file not found exception.
Ensure the file is always closed using the finally block, whether an exception occurs or
not.
9. Handle KeyError when accessing non-existent keys in a dictionary.
10. numbers = ["10", "5", "xyz", "0", "3"]. Write a Python program that iterates through
the list. For each item, the program should attempt to:
• Convert the string to an integer.
• Divide 10 by that integer.
• the program should catch the exception and print: Error with input '<item>':
<error_message>
• The loop must continue processing the rest of the list regardless of exceptions,
without stopping.

You might also like