Error Handling and Exceptions

Site Admin · 11 Sep 2026 · 9 views

Error Handling and Exceptions

Errors Are Normal

No program is perfect, and well-written code anticipates problems: a missing file, invalid user input, or a failed network request. Python uses exceptions to signal these situations. When an exception is raised and nothing handles it, the program stops with a traceback. The goal of error handling is to respond gracefully instead of crashing.

try:
    number = int(input("Enter a number: "))
    print(10 / number)
except ValueError:
    print("That was not a valid number.")
except ZeroDivisionError:
    print("You cannot divide by zero.")

The try block holds code that might fail. Each except block catches a specific exception type and runs its own recovery logic. Here a non-numeric input raises ValueError, and dividing by zero raises ZeroDivisionError.

Catching and Inspecting Errors

You can capture the exception object to inspect details. Writing except Exception as e is a common way to catch everything, but it can hide bugs, so catch the most specific types you expect first and leave a general handler last.

try:
    with open("missing.txt") as f:
        print(f.read())
except FileNotFoundError as e:
    print(f"Could not open file: {e}")

else and finally

An else block runs only when the try block succeeds, which keeps success logic separate from failure handling. A finally block always runs, whether the code succeeded or failed, making it ideal for cleanup such as closing resources.

try:
    result = 100 // int(input("Enter divisor: "))
except ValueError:
    print("Bad number")
else:
    print(f"Result: {result}")
finally:
    print("Cleanup done")

Raising Your Own Exceptions

When you detect an impossible state, raise an exception yourself so callers can handle it consistently. Defining custom exception classes becomes useful in larger projects.

def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    return age

Key Points

  • Exceptions stop the program unless a try/except block catches them.
  • Catch specific exception types like ValueError and FileNotFoundError before general ones.
  • else runs on success; finally always runs for cleanup.
  • Raise exceptions with raise when you detect invalid states.
  • Use tracebacks as a starting point to locate and understand bugs.
Share this post:

Comments (0)

Please login or register to comment.