Back to course

Introduction to Error Handling: `try` and `except`

Python Programming: The 0 to Hero Bootcamp

Error Handling: Dealing with Exceptions

When a Python program encounters a situation it cannot handle (like dividing by zero, trying to access a non-existent file, or converting invalid input), it raises an Exception (or error).

If unhandled, the exception causes the program to crash. Error handling allows us to gracefully manage these failures.

The try...except Block

python try: # Code that might raise an exception risky_operation() except ExceptionType as e: # Code that runs if the exception occurs handle_error(e)

Example: Handling Division by Zero

python num1 = 10 num2 = 0

try: result = num1 / num2 print(f"Result: {result}") except ZeroDivisionError: print("Error: Cannot divide by zero.") result = 0

print(f"Calculation finished. Final result: {result}")

Catching Specific vs. General Exceptions

It is always better to catch specific exceptions rather than broad ones.

python data = [1, 2, 3]

try: # 1. Potential ZeroDivisionError # 2. Potential IndexError item = data[4]

except IndexError: print("Attempted to access list index out of range.") except Exception as e: # Catch any other unexpected error type print(f"An unexpected error occurred: {e}")