P

Exception Handling

Python syntax guide

Error handling with try/except blocks in Python

Exception Handling

Error handling with try/except blocks in Python

Python exception handling (python)
        
          # Basic exception handling
try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")

# Multiple exception types
try:
    number = int("not_a_number")
except (ValueError, TypeError) as e:
    print(f"Conversion error: {e}")

# Catch all exceptions (not recommended)
try:
    risky_operation()
except Exception as e:
    print(f"Something went wrong: {e}")

# Finally block (always executes)
try:
    file = open("example.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found")
finally:
    file.close()  # Always close the file

# Better way with context manager
try:
    with open("example.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("File not found")
    content = ""

# Custom exceptions
class CustomError(Exception):
    """Custom exception class"""
    pass

def validate_age(age):
    if age < 0:
        raise CustomError("Age cannot be negative")
    if age > 150:
        raise ValueError("Age seems unrealistic")

try:
    validate_age(-5)
except CustomError as e:
    print(f"Custom error: {e}")

# Exception chaining
try:
    try:
        int("invalid")
    except ValueError:
        raise RuntimeError("Conversion failed") from ValueError("Invalid input")
except RuntimeError as e:
    print(f"Chained exception: {e}")
    print(f"Caused by: {e.__cause__}")
        
      

Explanation

Python uses exceptions for error handling. finally blocks execute regardless of exceptions. Context managers (with statement) handle resource cleanup automatically.

Common Use Cases

  • Input validation
  • File operations
  • Network operations
  • Resource management

Related Python Syntax

Master Exception Handling in Python

Understanding exception handling is fundamental to writing clean and efficient Python code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.

Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using exception handling effectively in your Python projects.

Key Takeaways

  • Input validation
  • File operations
  • Network operations