Python Practice › Exception Handling Programs
Python Exception Handling Programs with Solutions
20 exception handling programs: catching specific errors, else and finally, raising and re-raising, custom exceptions, retries and safe input parsing. Each solution runs both the success path and the failure path so you can see every branch.
Before you start
Read the Exception Handling lesson first if the topic is new to you.
All programs
- #1Handle division by zero
Write a Python program that divides two numbers and prints a friendly message when the divisor is 0.Easy - #2Handle invalid integer input
Write a Python program that converts text to an integer and reports invalid values.Easy - #3Handle a missing dictionary key
Write a Python program that reads a key from a dictionary and handles a missing key.Easy - #4Handle an index out of range
Write a Python program that reads a list item by index and handles invalid indexes.Easy - #5Several except blocks
Write a Python function that handles TypeError and ZeroDivisionError separately.Easy - #6Catch several errors in one block
Write a Python program that catches ValueError and TypeError in one except block.Easy - #7Use the else block
Write a Python program that useselseto run code only when no exception occurred.Easy - #8Use the finally block
Write a Python program that showsfinallyalways runs.Easy - #9Raise an exception
Write a Python function that raises ValueError for an invalid age.Easy - #10Custom exception class
Write a Python program with a customInsufficientBalanceError.Medium - #11Log and re-raise
Write a Python program that logs an error and then re-raises it to the caller.Easy - #12Chain exceptions with raise from
Write a Python program that converts a low-level error into a clearer one and keeps the cause.Medium - #13Handle a missing file
Write a Python program that opens a file and handles the case where it does not exist.Easy - #14Retry on failure
Write a Python program that retries an unreliable operation up to 3 times.Medium - #15Use assert for checks
Write a Python program that usesassertto check a condition and handles the AssertionError.Easy - #16Ask until the input is valid
Write a Python program that keeps asking for a number until a valid one is entered.Easy - #17Print exception details
Write a Python program that prints the type, message and line of a caught exception.Easy - #18Clean-up with a context manager
Write a Python program showing that awithblock closes a file even when an error happens inside it.Easy - #19Collect several errors
Write a Python program that validates several fields and reports every error at once.Medium - #20Exception hierarchy order
Write a Python program showing why specific exceptions must be caught before general ones.Easy