Useful Data Tips

Python Try Except

🐍 Python ⏱️ 25 sec read

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

ExceptionWhen It Occurs
ValueErrorInvalid value type
TypeErrorWrong type operation
KeyErrorDictionary key missing
IndexErrorList index out of range
FileNotFoundErrorFile doesn't exist
ZeroDivisionErrorDivision by zero
AttributeErrorInvalid attribute

Best Practices

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