LearnFrenzy
Sign in Take a free test

Exception Handling · Exercise 4 of 4

Exception Handling Exception Handling Coding Problems

  • 10 questions
  • Page 1 of 1
  • Answers explained
0Attempted
0Correct
0Wrong
Directions

Python programs that handle errors gracefully: input validation, custom exceptions, chaining, retries and clean-up. Write each one yourself first, then open the solution – every solution was run on Python 3, the output shown is the real output, and Run opens it in the online Python compiler.

Question 1 Easy

Read lines until a valid whole number between 1 and 10 is entered, explaining each rejection.

Question page & discussion
Question 2 Easy

Divide each pair of values, reporting division by zero and wrong types without stopping the program.

Question page & discussion
Question 3 Medium

Write a BankAccount class whose withdraw() raises a custom InsufficientBalanceError (with the shortfall) or ValueError for a non-positive amount, and process a list of withdrawals.

Question page & discussion
Question 4 Medium

Validate name, age and email of each registration with small functions that raise ValueError, collecting every error message rather than stopping at the first.

Question page & discussion
Question 5 Medium

Parse "key = value" lines into a dict of ints, skipping blank lines and comments, and report the line number and reason for each bad line.

Question page & discussion
Question 6 Hard

Write retry(func, attempts) that calls func until it succeeds, catching ConnectionError, and re-raises the last error after the final attempt. Test it with a simulated flaky connection.

Question page & discussion
Question 7 Hard

Write load_order(data) that raises a custom OrderError (chained from the original) when the order dict lacks a field or has a non-numeric quantity, and report the cause.

Question page & discussion
Question 8 Hard

Write a context manager class that prints "start" and "end" around a block, logs any ValueError raised inside and suppresses it, but lets other exceptions through.

Question page & discussion
Question 9 Medium

Evaluate expressions such as "8 / 2", catching malformed input, unknown operators, bad numbers and division by zero, each with its own message.

Question page & discussion
Question 10 Medium

Simulate acquiring and releasing a lock around tasks: the lock must be released even when a task fails, and failures are reported after clean-up.

Question page & discussion
All exercises doneBack to Exception HandlingRevise the concepts or pick another topic

Ready to test your Programming?

Timed online tests with instant scores and explanations.

Search LearnFrenzy

Esc

Quick links