Python Try Except
What is Try Except?
Try except handles errors gracefully in Python. Code in `try` block runs; if error occurs, `except` block catches it and program continues.
Basic Syntax
try:
# Code that might cause error
risky_operation()
except:
# Handle the error
print("An error occurred")
Simple Example
# Without try except - program crashes
number = int(input("Enter number: ")) # User enters "abc" → crash!
# With try except - handles error gracefully
try:
number = int(input("Enter number: "))
print(f"You entered: {number}")
except:
print("That's not a valid number!")
Catching Specific Exceptions
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
try:
number = int("abc")
except ValueError:
print("Invalid number format!")
try:
file = open("missing.txt")
except FileNotFoundError:
print("File not found!")
Multiple Except Blocks
try:
file = open("data.txt")
number = int(file.read())
result = 100 / number
except FileNotFoundError:
print("File doesn't exist")
except ValueError:
print("File doesn't contain a number")
except ZeroDivisionError:
print("Number cannot be zero")
except Exception as e:
print(f"Unexpected error: {e}")
Try Except Else Finally
try:
file = open("data.txt")
data = file.read()
except FileNotFoundError:
print("File not found")
else:
# Runs if NO exception occurred
print(f"Successfully read: {data}")
finally:
# ALWAYS runs (cleanup code)
if 'file' in locals():
file.close()
print("Done")
Getting Error Details
try:
result = 10 / 0
except Exception as e:
print(f"Error type: {type(e).__name__}")
print(f"Error message: {e}")
print(f"Full details: {repr(e)}")
Common Exceptions
| Exception | When It Occurs |
|---|---|
| ValueError | Invalid value type |
| TypeError | Wrong type operation |
| KeyError | Dictionary key missing |
| IndexError | List index out of range |
| FileNotFoundError | File doesn't exist |
| ZeroDivisionError | Division by zero |
| AttributeError | Invalid attribute |
Best Practices
- Be specific: Catch specific exceptions, not generic Exception
- Don't hide errors: Log or report them
- Use finally: For cleanup (close files, connections)
- Don't use as control flow: Use for actual errors only
- Provide helpful messages: Tell users what went wrong
Real-World Examples
# File reading with error handling
try:
with open("data.csv") as f:
data = f.read()
except FileNotFoundError:
print("Creating new file...")
data = ""
except PermissionError:
print("No permission to read file")
# API request with error handling
import requests
try:
response = requests.get(url, timeout=5)
response.raise_for_status()
data = response.json()
except requests.Timeout:
print("Request timed out")
except requests.HTTPError as e:
print(f"HTTP error: {e}")
except requests.RequestException as e:
print(f"Request failed: {e}")
Key Takeaways:
- try except prevents program crashes from errors
- Catch specific exceptions for better error handling
- else block: Runs only if no exception
- finally block: Always runs (cleanup code)
- Use as e to get error details
- Don't use bare except: - catch specific errors