Python Practice Set (Part 13): Error Handling and Exceptions
- Anubhav Somani
- Sep 3
- 2 min read

Writing Robust Python Code: A Guide to Handling Errors and Exceptions
Welcome to Part 13 of our Python coding series! So far, our code has assumed a "perfect world" where user input is always correct and files always exist. But in the real world, things go wrong. A user might enter text instead of a number, or a network connection might fail. Exception Handling allows you to gracefully manage these errors instead of letting your program crash. By learning to use try, except, else, and finally, you can build resilient and user-friendly applications.
1. The Basic try-except Block
Write a function safe_divide that takes two numbers, numerator and denominator, as input. It should attempt to divide the numerator by the denominator. If a ZeroDivisionError occurs (i.e., the denominator is 0), it should print an error message like "Error: Cannot divide by zero." instead of crashing. If the division is successful, it should print the result.
2. Handling Multiple Specific Exceptions
Create a function get_integer_from_user that asks the user to "Enter a number:". The function should:
Use a try-except block to handle two potential errors.
If the user enters text that cannot be converted to an integer, it should catch the ValueError and print "Invalid input. Please enter a whole number."
If the user presses Ctrl+C to interrupt the program, it should catch the KeyboardInterrupt and print "Operation cancelled by user."
If the input is valid, it should print the number the user entered.
3. Using the else Block
The else block in a try-except structure runs only if no exceptions were raised in the try block. Rewrite the safe_divide function from Question 1. This time, the try block should only contain the division operation itself. The print(result) statement should be moved to the else block, ensuring it only runs on a successful division. The except block remains the same.
4. The finally Block for Cleanup
The finally block runs no matter what—whether an exception occurred or not. This is perfect for cleanup actions, like closing a file. Write a function read_and_close that takes a filename. It should:
Print "Opening file..."
Use a try block to attempt to open and read the file's content.
Use an except block to catch a FileNotFoundError.
Use a finally block to print "File operation complete. Closing file." This message should appear whether the file was found or not.
5. Raising a Custom Exception
Sometimes, you need to create your own error conditions. Write a function set_age that takes an age as input.
If the age is negative, the function should raise a ValueError with the custom message "Age cannot be negative."
If the age is valid (0 or greater), it should print "Age has been set."
Wrap the function call in a try-except block to catch the ValueError you raised and print its message.
Luckey Link - https://amzn.to/4lXO9zo
Comments