P

Manejo de Excepciones

Python syntax guide

Manejo de errores con bloques try/except en Python

Manejo de Excepciones

Manejo de errores con bloques try/except en Python

Python manejo de excepciones (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 usa excepciones para el manejo de errores. Los bloques finally se ejecutan independientemente de las excepciones. Los administradores de contexto (sentencia with) manejan la limpieza de recursos automáticamente.

Common Use Cases

  • Validación de entrada
  • Operaciones de archivo
  • Operaciones de red
  • Gestión de recursos

Related Python Syntax

Master Manejo de Excepciones in Python

Understanding manejo de excepciones 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 manejo de excepciones effectively in your Python projects.

Key Takeaways

  • Validación de entrada
  • Operaciones de archivo
  • Operaciones de red