Python Exceptions

Carson West

Exception Handling Examples

Python Exceptions Python Exceptions are events that occur during the execution of a program that disrupt the normal flow of instructions. They are a way for Python to signal that something unexpected or erroneous has happened. Handling exceptions gracefully is crucial for writing robust and reliable code.

Key Concepts:

try:
  # Code that might raise an exception
  result = 10 / 0  
except ZeroDivisionError:
  # Code to handle the specific exception
  print("Error: Division by zero!")
except Exception as e: #Catches any other exception.  Should be used cautiously.
    print(f"An unexpected error occurred: {e}")
else: #Optional block that executes only if no exception occurred.
    print(f"Result: {result}")
finally: #Optional block that ALWAYS executes, regardless of exceptions.  Good for cleanup.
    print("This always runs.")
def validate_age(age):
  if age < 0:
    raise ValueError("Age cannot be negative")
  # ... rest of the function ...

Related Notes: