Of course! The except statement is a fundamental part of Python's error handling mechanism, known as exception handling. It allows your program to catch and handle errors gracefully, instead of crashing.

Let's break it down for Python 3.5, which is a very common version for many projects.
The Core Concept: The try...except Block
The basic idea is to "try" to run a block of code that you think might cause an error. If an error (an exception) occurs, you "catch" it with an except block and decide what to do next.
Basic Syntax
try:
# Code that might cause an error
risky_code()
except SomeError:
# Code to run if SomeError occurs
handle_the_error()
Common Examples
Let's look at the most common ways to use except.
Example A: Catching a Specific Exception
This is the best practice. You catch the specific error you expect, so you don't accidentally hide other, unexpected problems.

# Let's say we have a list and we want to access an element at an index.
my_list = [10, 20, 30]
try:
# This will cause an IndexError because index 5 doesn't exist.
print("Trying to access element at index 5...")
value = my_list[5]
print("This line will not be reached.")
except IndexError:
# This block will ONLY run if an IndexError occurs.
print("Caught an IndexError! The list doesn't have an element at that index.")
print("Let's use a safe default instead.")
value = 0
print(f"The final value is: {value}")
Output:
Trying to access element at index 5...
Caught an IndexError! The list doesn't have an element at that index.
Let's use a safe default instead.
The final value is: 0
Example B: Catching Multiple Specific Exceptions
You can handle different errors in different ways.
try:
# User input is always a string, so this will cause a TypeError.
user_input = "hello"
number = int(user_input)
result = 100 / number
except ValueError:
print("Error: You did not enter a valid number.")
except TypeError:
print("Error: The input was of the wrong type (e.g., trying to add a string to a number).")
except ZeroDivisionError:
print("Error: You cannot divide by zero.")
If you run this code, it will print: Error: You did not enter a valid number. because int("hello") raises a ValueError.
Example C: Catching Any Exception (Use with Caution!)
You can use a bare except: to catch any exception. This is generally discouraged because it can hide bugs in your code. It's better to catch specific exceptions when you can.

try:
# This could raise many different errors.
result = 10 / "a"
except Exception as e:
# 'e' is a variable that holds the exception object.
# It's good practice to log or print the error.
print(f"An unexpected error occurred: {e}")
print(f"Type of error: {type(e)}")
Output:
An unexpected error occurred: unsupported operand type(s) for /: 'int' and 'str'
Type of error: <class 'TypeError'>
Note: In Python 3, except Exception, e: is the old 2.x syntax. The modern syntax in 3.5+ is except Exception as e:.
The Full try...except...else...finally Structure
Python provides more keywords to make exception handling even more powerful.
try: The code block you want to monitor for errors.except: The block that runs if an error occurs.else: This is a key feature. The code in theelseblock runs only if thetryblock completes without raising any exceptions.finally: The code in this block runs no matter what. It always executes, whether an error occurred or not, whether it was caught or not. It's typically used for cleanup actions (like closing a file or a network connection).
Example: Using else and finally
def process_file(filename):
print(f"--- Attempting to process '{filename}' ---")
try:
# This might raise FileNotFoundError
f = open(filename, 'r')
# This might raise other errors, but let's assume it doesn't.
content = f.read()
# If we get here, the file was opened successfully.
except FileNotFoundError:
print("ERROR: The file was not found.")
except IOError:
print("ERROR: Could not read the file.")
else:
# This runs ONLY if no exceptions were raised in the 'try' block.
print("File processed successfully!")
print(f"Content length: {len(content)}")
finally:
# This runs NO MATTER WHAT.
print("Cleaning up...")
# It's crucial to close the file if it was opened.
# We check if 'f' exists to avoid an error if open() failed.
if 'f' in locals():
f.close()
print("Cleanup complete.")
# --- Test Cases ---
# Case 1: File exists
process_file('my_test_file.txt') # You would need to create this file to see success
print("\n" + "="*30 + "\n")
# Case 2: File does not exist
process_file('non_existent_file.txt')
Output (if my_test_file.txt exists):
--- Attempting to process 'my_test_file.txt' ---
File processed successfully!
Content length: 25
Cleaning up...
Cleanup complete.
==============================
--- Attempting to process 'non_existent_file.txt' ---
ERROR: The file was not found.
Cleaning up...
Cleanup complete.
Raising Your Own Exceptions (raise)
You can also force an exception to be raised using the raise keyword. This is useful when your program is in an invalid state and cannot continue.
def set_age(age):
if not isinstance(age, int):
# We raise a TypeError if the input is not an integer.
raise TypeError("Age must be an integer.")
if age < 0 or age > 120:
# We raise a ValueError if the age is out of a reasonable range.
raise ValueError("Age must be between 0 and 120.")
print(f"Age set to: {age}")
try:
set_age(25) # This is fine
set_age(-5) # This will raise a ValueError
except ValueError as ve:
print(f"Caught a validation error: {ve}")
except TypeError as te:
print(f"Caught a type error: {te}")
Output:
Age set to: 25
Caught a validation error: Age must be between 0 and 120.
Summary for Python 3.5
| Keyword | Purpose | Example |
|---|---|---|
try |
Wraps code that might fail. | try: x = 1 / 0 |
except |
Catches and handles a specific error. | except ZeroDivisionError: print("Can't divide by zero") |
raise |
Forces an exception to occur. | if age < 0: raise ValueError("Invalid age") |
as |
Assigns the caught exception to a variable. | except Exception as e: print(e) |
else |
Runs if the try block succeeds. |
try: except: else: print("All good!") |
finally |
Runs no matter what (for cleanup). | try: finally: print("Cleanup") |
