Open-Source Python Lesson #6: Errors, Exceptions, Try, Except, Else, and Finally

Open-Source Python Lesson #6 teaches errors and exception handling with try, except, else, and finally. Robust programs should anticipate recoverable failures instead of crashing whenever input, files, telemetry, or other runtime conditions are imperfect.

Bitcoin Mining Example: Validate Telemetry

raw_hashrate = "offline"

try:
    hashrate_th = float(raw_hashrate)
    print("Hashrate:", hashrate_th, "TH/s")
except ValueError:
    print("Miner returned non-numeric hashrate data")

Converting a non-numeric string with float() raises ValueError. Catching that specific exception lets a monitoring program respond deliberately.

Gaming Example: Protect Player Input

choice = "turbo"

try:
    selected_slot = int(choice)
except ValueError:
    print("Inventory slot must be a number")

Sports Example: Avoid Division by Zero

points = 24
games_played = 0

try:
    average = points / games_played
except ZeroDivisionError:
    print("Average unavailable until a game is played")

else: Run Only After Success

temperature = "72"

try:
    temperature_c = int(temperature)
except ValueError:
    print("Invalid temperature")
else:
    print("Valid telemetry:", temperature_c, "C")

The else block runs when the try block completes without raising an exception.

finally: Cleanup That Must Run

connection_open = True

try:
    print("Reading miner telemetry")
finally:
    connection_open = False
    print("Connection closed")

finally is intended for cleanup that should run whether an exception occurs or not.

Catch Specific Exceptions

Prefer specific handlers such as ValueError, ZeroDivisionError, or OSError when you know which failures you can meaningfully handle. Broad exception handling can hide programming mistakes.

Video Lesson

Programming with Mosh’s widely viewed Python beginner course includes a dedicated Exceptions chapter at approximately 2:53:42.

Practice

  1. Handle invalid ASIC hashrate telemetry with ValueError.
  2. Protect numeric game input with try/except.
  3. Handle a sports average when games played is zero.
  4. Add an else block that reports successful parsing.
  5. Add a finally block representing connection cleanup.

Key Takeaway

try contains code that may fail, except handles selected exceptions, else runs after a successful try block, and finally provides cleanup that runs regardless of the outcome.

Leave a comment