Home Tutorials Python Tutorial Try and Except
Try and Except

Try and Except


Exception Handling

Definition: The try...except block is used in Python to handle errors and exceptions. It allows a program to catch unexpected errors during execution and respond gracefully instead of crashing completely.

Why: Real-world programs interact with unpredictable inputs, missing files, or network drops. Teaching exception handling early ensures you build resilient applications that can report an issue to the user and keep running safely rather than abruptly shutting down.

How It Works

  • The try Block: You place the code that *might* cause an error inside this block. Python will attempt to run it normally.
  • The except Block: If an error occurs inside the try block, Python immediately stops execution there and jumps straight to this block to run the recovery code.

Example

try:
    num = int(input("Enter a number: "))
    print(num)
except ValueError:
    print("Please enter a valid number")

Explanation

  • The Code Inside try: The input() function reads text from the user, and int() tries to convert that text into a whole number.
  • The Potential Error: If a user types "hello" instead of a number, the int() function cannot convert it and throws a ValueError.
  • The Catch: Because we specified except ValueError:, Python catches that specific error and prints a helpful message rather than showing a confusing technical error screen to the user.

Expanding the Control Flow

You can make exception handling more robust by adding optional else and finally blocks:

try:
    file = open("data.txt", "r")
except FileNotFoundError:
    print("Error: The file does not exist.")
else:
    print("File read successfully!")  # Runs ONLY if the try block succeeds without errors
finally:
    print("Execution complete.")      # ALWAYS runs, no matter what happens above

Key Notes

  • Catching Specific Errors: It is best practice to catch specific exceptions (like ValueError or ZeroDivisionError) rather than using a bare except: block, which could accidentally hide unrelated bugs in your code.
  • The as Keyword: You can capture the error message itself into a variable to log it or print it (e.g., except ValueError as error:).
  • If no error occurs inside the try block, the except block is completely skipped.
Example

🏋️ Test Yourself With Exercises

Take our quiz on Try and Except to test your knowledge.

Exercise »