P

Tratamento de Exceções

Python Syntax Guide

Tratamento de erros com blocos try/except em Python

Tratamento de Exceções

Tratamento de erros com blocos try/except em Python

Python tratamento de exceções (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 exceções para tratamento de erros. Os blocos finally executam independentemente das exceções. Os gerenciadores de contexto (instrução with) lidam com a limpeza de recursos automaticamente.

Common Use Cases

  • Validação de entrada
  • Operações de arquivo
  • Operações de rede
  • Gerenciamento de recursos

Related Python Syntax

Master Tratamento de Exceções in Python

Understanding Tratamento de Exceções 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 Tratamento de Exceções effectively in your Python projects.

Key Takeaways

  • Validação de entrada
  • Operações de arquivo
  • Operações de rede