🎉 Welcome to PyVerse! Start Learning Today

Exception Handling (try, except, finally)

1) Why do we need exceptions?

  • Programs sometimes face surprises: a user types letters instead of a number, a file doesn't exist, or a number divides by zero.
  • An exception is Python's way of saying, "Something went wrong at runtime."
  • Without handling exceptions, your program may crash. With try/except/finally, you can catch problems and keep going smoothly.

2) The main ideas

  • try: Put code here that might cause an error.
  • except: If an error happens, Python jumps here so you can handle it.
  • finally: This always runs at the end, whether there was an error or not. It's great for cleanup (like closing files or printing a "Done" message).

3) Basic syntax

try: risky_code() except SomeSpecificError: handle_that_error() except AnotherError as e: print("Details:", e) finally: always_runs()

Note:

  • Catch specific errors first. Use a generic except Exception as e only as a last fallback.
  • You can also use else: it runs only if no exception happened.

Easy and clean code examples

A) Converting input safely (ValueError)

print("Enter your age:") try: age = int(input("> ")) print("You are", age, "years old.") except ValueError: print("Please enter numbers only.") finally: print("Thanks for using the age checker!")

B) Dividing numbers (multiple except, with else and finally)

try: a = int(input("Enter the numerator: ")) b = int(input("Enter the denominator: ")) result = a / b except ValueError: print("Only whole numbers are allowed.") except ZeroDivisionError: print("You cannot divide by zero.") else: print("Result:", result) finally: print("Calculation attempt finished.")

C) Seeing the actual error message (as e)

items = ["apple", "banana", "cherry"] try: print(items[5]) # This index doesn't exist except IndexError as e: print("Oops! Index problem:", e) finally: print("Index check complete.")

D) Cleanup with finally (closing a file)

file = None try: file = open("data.txt", "r") content = file.read() print("File length:", len(content)) except FileNotFoundError: print("data.txt not found. Make sure the file exists next to your script.") finally: if file is not None: file.close() print("File closed.") print("Done reading attempt.")

Note: In real projects, we often prefer with open(...) as f: because it auto-closes the file. finally is still useful for many other kinds of cleanup.

Mini Project: Safe Calculator (loop + try/except/finally)

Goal: Build a simple calculator that keeps running until the user quits. It handles wrong inputs and division by zero without crashing, and always prints a neat divider line in finally.

Steps:

  • Ask for two numbers.
  • Ask for an operation: +, -, *, /
  • Handle these errors:
    • ValueError for non-numeric input
    • ZeroDivisionError for dividing by zero
  • Use finally to print a divider every round.
  • Let the user type q to quit.

Code:

print("Welcome to SafeCalc! Type q at any prompt to quit.") while True: try: left = input("Left number: ") if left.lower() == "q": break right = input("Right number: ") if right.lower() == "q": break op = input("Operation (+, -, *, /): ") if op.lower() == "q": break a = float(left) b = float(right) if op == "+": result = a + b elif op == "-": result = a - b elif op == "*": result = a * b elif op == "/": result = a / b # may raise ZeroDivisionError if b == 0.0 else: print("Unknown operation. Choose from +, -, *, /.") continue print("Answer:", result) except ValueError: print("Please enter valid numbers for left and right.") except ZeroDivisionError: print("Cannot divide by zero. Try a different denominator.") finally: print("-----") # Always prints, even if there was an error print("Goodbye from SafeCalc!")

Challenge ideas:

  • Add power (^) and modulo (%) operations.
  • Count how many successful calculations happened.
  • Log each attempt to a list; at the end, print the history.

Summary

  • Exceptions are runtime problems. Use try to attempt risky code.
  • except catches specific errors and lets your program respond, not crash.
  • finally always runs, perfect for cleanup or final messages.
  • Write specific except blocks first; only use a general except Exception as e at the end if needed.
  • Practice makes it natural—wrap tricky code, handle what can go wrong, and keep your programs friendly and reliable.

Loading quizzes...