Ask until the input is valid

Ask until the input is valid

EasyException Handling Programs · 16 of 20

Write a Python program that keeps asking for a number until a valid one is entered.

Input
"ten", "-4", "12"
Output
Quantity: ten
Please type a whole number
Quantity: -4
Quantity must be positive
Quantity: 12
Ordered 12

Approach

  1. Loop with while True, continue on bad input and break on good input.

Solution

Python
while True:    text = input("Quantity: ")    try:        qty = int(text)    except ValueError:        print("Please type a whole number")        continue    if qty <= 0:        print("Quantity must be positive")        continue    breakprint("Ordered", qty)
Outputtyped input: ten, -4, 12
Quantity: ten
Please type a whole number
Quantity: -4
Quantity must be positive
Quantity: 12
Ordered 12

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs

Handle a missing file

Handle a missing file

EasyException Handling Programs · 13 of 20

Write a Python program that opens a file and handles the case where it does not exist.

Output
exists.txt -> hello
missing.txt -> not found

Approach

  1. Catch FileNotFoundError.

Solution

Python
for name in ["exists.txt", "missing.txt"]:    if name == "exists.txt":        with open(name, "w") as f:            f.write("hello")    try:        with open(name) as f:            print(name, "->", f.read())    except FileNotFoundError:        print(name, "-> not found")
Output
exists.txt -> hello
missing.txt -> not found

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs

Retry on failure

Retry on failure

MediumException Handling Programs · 14 of 20

Write a Python program that retries an unreliable operation up to 3 times.

Output
attempt 1 failed: slow
attempt 2 failed: slow
attempt 3 -> OK

Approach

  1. Loop over attempts; stop on success with break; else reports total failure.

Solution

Python
results = iter([TimeoutError("slow"), TimeoutError("slow"), "OK"]) def call_service():    r = next(results)    if isinstance(r, Exception):        raise r    return r for attempt in range(1, 4):    try:        print("attempt", attempt, "->", call_service())        break    except TimeoutError as e:        print("attempt", attempt, "failed:", e)else:    print("all attempts failed")
Output
attempt 1 failed: slow
attempt 2 failed: slow
attempt 3 -> OK

Line by line

Lines 1-7

A fake service that fails twice and then succeeds.

Lines 9-17

The loop’s else would run only if no attempt succeeded.

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs

Use assert for checks

Use assert for checks

EasyException Handling Programs · 15 of 20

Write a Python program that uses assert to check a condition and handles the AssertionError.

Output
450.0
Error: percent must be 0-100

Approach

  1. assert condition, message raises AssertionError when the condition is false.

Solution

Python
def apply_discount(price, percent):    assert 0 <= percent <= 100, "percent must be 0-100"    return price * (1 - percent / 100) print(apply_discount(500, 10))try:    apply_discount(500, 150)except AssertionError as e:    print("Error:", e)
Output
450.0
Error: percent must be 0-100
Watch out

Python skips assert statements when run with -O, so use them for internal checks and tests, not for validating user input.

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs

Custom exception class

Custom exception class

MediumException Handling Programs · 10 of 20

Write a Python program with a custom InsufficientBalanceError.

Output
Declined: balance 500 is less than 800 | short by 300

Approach

  1. Inherit from Exception and store useful details on the object.

Solution

Python
class InsufficientBalanceError(Exception):    def __init__(self, balance, amount):        super().__init__(f"balance {balance} is less than {amount}")        self.shortfall = amount - balance def withdraw(balance, amount):    if amount > balance:        raise InsufficientBalanceError(balance, amount)    return balance - amount try:    withdraw(500, 800)except InsufficientBalanceError as e:    print("Declined:", e, "| short by", e.shortfall)
Output
Declined: balance 500 is less than 800 | short by 300

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs

Log and re-raise

Log and re-raise

EasyException Handling Programs · 11 of 20

Write a Python program that logs an error and then re-raises it to the caller.

Output
log: could not open missing.txt
caller handled: No such file or directory

Approach

  1. A bare raise inside except re-raises the same exception.

Solution

Python
def load(path):    try:        return open(path).read()    except FileNotFoundError:        print("log: could not open", path)        raise try:    load("missing.txt")except FileNotFoundError as e:    print("caller handled:", e.strerror)
Output
log: could not open missing.txt
caller handled: No such file or directory

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs

Chain exceptions with raise from

Chain exceptions with raise from

MediumException Handling Programs · 12 of 20

Write a Python program that converts a low-level error into a clearer one and keeps the cause.

Output
port is missing or not a number | caused by: ValueError

Approach

  1. raise NewError(...) from e stores the original in __cause__.

Solution

Python
class ConfigError(Exception):    pass def read_port(settings):    try:        return int(settings["port"])    except (KeyError, ValueError) as e:        raise ConfigError("port is missing or not a number") from e try:    read_port({"port": "eighty"})except ConfigError as e:    print(e, "| caused by:", type(e.__cause__).__name__)
Output
port is missing or not a number | caused by: ValueError

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs

Raise an exception

Raise an exception

EasyException Handling Programs · 9 of 20

Write a Python function that raises ValueError for an invalid age.

Input
25, -3
Output
age set: 25
rejected: age must be positive, got -3

Approach

  1. raise ValueError("message").

Solution

Python
def set_age(age):    if age < 0:        raise ValueError(f"age must be positive, got {age}")    return age for a in [25, -3]:    try:        print("age set:", set_age(a))    except ValueError as e:        print("rejected:", e)
Output
age set: 25
rejected: age must be positive, got -3

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs

Use the else block

Use the else block

EasyException Handling Programs · 7 of 20

Write a Python program that uses else to run code only when no exception occurred.

Input
"25", "x"
Output
25 squared is 625
x is not a number

Approach

  1. else runs after try only if nothing was raised.

Solution

Python
for text in ["25", "x"]:    try:        n = int(text)    except ValueError:        print(text, "is not a number")    else:        print(text, "squared is", n * n)
Output
25 squared is 625
x is not a number

Line by line

Lines 6-7

Keeping the follow-up work in else means a bug there is not hidden by the except.

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs

Use the finally block

Use the finally block

EasyException Handling Programs · 8 of 20

Write a Python program that shows finally always runs.

Output
  result: 25.0
  clean-up done
  error handled
  clean-up done

Approach

  1. Run the function once successfully and once with an error.

Solution

Python
def process(value):    try:        print("  result:", 100 / value)    except ZeroDivisionError:        print("  error handled")    finally:        print("  clean-up done") process(4)process(0)
Output
  result: 25.0
  clean-up done
  error handled
  clean-up done

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs