Gestion des Exceptions
Python Syntax Guide
Gestion des erreurs avec des blocs try/except en Python
Gestion des Exceptions
Gestion des erreurs avec des blocs try/except en 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
Common Use Cases
- Validation des entrées
- Opérations de fichier
- Opérations réseau
- Gestion des ressources
Related Python Syntax
Variables & Data Types
Python variables and data types
Control Flow
Conditional statements and loops in Python
Functions & Generators
Function definitions and generator functions in Python
Classes & OOP
Object-oriented programming with classes in Python
Modules & Packages
Importing and organizing code with modules and packages
Master Gestion des Exceptions in Python
Understanding Gestion des Exceptions 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 Gestion des Exceptions effectively in your Python projects.
Key Takeaways
- Validation des entrées
- Opérations de fichier
- Opérations réseau