Published on

4. An exception in Python

Authors

4. Can you explain how an exception can be caught in a Python program?

Yes! In Python, exceptions are caught using the try and except blocks. This mechanism allows your program to handle errors gracefully instead of crashing when an error occurs.


🧱 Basic Syntax:

try:
    # Code that might raise an exception
    risky_operation()
except SomeException:
    # Code that runs if that exception occurs
    handle_error()

✅ Example:

try:
    number = int(input("Enter a number: "))
    result = 10 / number
except ValueError:
    print("That's not a valid number.")
except ZeroDivisionError:
    print("You can't divide by zero.")
else:
    print("Result is:", result)
finally:
    print("This block always runs.")

🧠 Explanation:

  • try: Code that might cause an exception.
  • except: Handles a specific type of exception.
  • else: Runs if no exception was raised in the try block.
  • finally: Always runs, regardless of whether an exception occurred or not (e.g., for cleanup).

try:
    risky_operation()
except Exception as e:
    print("An error occurred:", e)

Use this with caution — it's better to catch specific exceptions when possible.