try and except

You wrap the code that might fail in a try block. If an error occurs, Python stops running the try block and creates an Exception Object that contains details about what went wrong (like the error message).

Python then jumps immediately to the except block, where you expect some type of an error. There are many types of errors that you can handle specifically, but the most general “catch-all” is simply called Exception.

try:
    number = int(input("Enter a number to divide 100 by: "))
    result = 100 / number
    print(f"Result: {result}")
except Exception as e:
    # 'Exception' is the type of error (the "catch-all" in this case)
    # 'as e' assigns the error message to the variable 'e'
    print(f"Something went wrong: {e}")

Python checks except blocks from top to bottom. Always go from the most specific error to the most generic. Use Exception as a last resort if there are no more specific alternatives.

try:
    number = int(input("Enter a number: "))
    print(100 / number)

except ValueError:
    # Runs if they typed "hello" instead of a number
    print("Error: That wasn't a valid number!")

except ZeroDivisionError:
    # Runs if they typed "0"
    print("Error: You cannot divide by zero!")

except Exception as e:
    # The 'Catch-All' fallback for anything else
    print(f"Unexpected error: {e}")

else and finally

You can add two more blocks:

  1. else: Runs only if the try block was successful (no errors).
  2. finally: Runs no matter what. This is critical for “cleanup” tasks, like closing a file or a database connection so you don’t leak memory.
try:
    number = int(input("Enter a number: "))
    result = 100 / number

except ValueError:
    print("Error: That wasn't a valid number!")

except ZeroDivisionError:
    print("Error: You cannot divide by zero!")

else:
    # This only runs if the user entered a valid, non-zero number
    print(f"Success! The result is {result}")

finally:
    # This runs regardless of success or failure
    # Perfect for "cleaning up" or resetting a system state
    print("System: Calculation attempt finished.")

raise

Sometimes, code is technically “correct” in Python, but it’s “wrong” for your app’s logic. You can use the raise keyword to trigger an error manually.

def create_account(password):
    if len(password) < 8:
        # We 'raise' a ValueError manually
        raise ValueError("Password is too short!")
    
    # Check if there is at least one digit in the string
    if not any(char.isdigit() for char in password):
        raise ValueError("Password must contain a number.")
    
    print("Account created!")

try:
    create_account("abc123")
except ValueError as e:
    print(f"Invalid Password: {e}")

Using try/except is not just about stopping crashes, it’s about intent. It tells other developers: “I know this part of the code is risky, and I have a plan for when it fails.”