๐Ÿ Python Examples - Comprehensive Code Library
โ† Back to PranavKulkarni.org
Lesson 5 ยท Fundamentals

Exception Handling

Learn to handle errors gracefully using try-except blocks and best practices for debugging.

What are Exceptions?

Exceptions are errors that occur during execution. If not handled, they crash your program.

Try-Except Blocks

Use try to wrap code that might fail and except to handle specific errors.

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

Finally and Else

finally always runs (great for cleanup like closing files), and else runs only if no exception occurred.

try:
    f = open("data.txt", "r")
except FileNotFoundError:
    print("File missing")
else:
    content = f.read()
finally:
    # This runs regardless of success or failure
    print("Cleanup complete")

Raising Exceptions

You can intentionally trigger an exception using raise.

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

โœ… Practice (15 minutes)

  • Write a program that asks for user input and tries to convert it to an integer.
  • Use try-except to handle cases where the user enters non-numeric text.
  • Create a function that raises a PermissionError if a user isn't an "admin".