P

Ausnahmebehandlung

Python Syntax Guide

Fehlerbehandlung mit try/except-Blöcken in Python

Ausnahmebehandlung

Fehlerbehandlung mit try/except-Blöcken in Python

Python ausnahmebehandlung (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 verwendet Ausnahmen für die Fehlerbehandlung. finally-Blöcke werden unabhängig von Ausnahmen ausgeführt. Kontextmanager (with-Anweisung) verwalten die Ressourcenbereinigung automatisch.

Common Use Cases

  • Eingabevalidierung
  • Dateioperationen
  • Netzwerkoperationen
  • Ressourcenverwaltung

Related Python Syntax

Master Ausnahmebehandlung in Python

Understanding Ausnahmebehandlung 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 Ausnahmebehandlung effectively in your Python projects.

Key Takeaways

  • Eingabevalidierung
  • Dateioperationen
  • Netzwerkoperationen