Error Handling Techniques
Introduction to Error Handling
Error handling is a critical aspect of robust Python programming, especially when dealing with string repetition operations. This section explores various techniques to gracefully manage and respond to potential errors.
Basic Exception Handling
Try-Except Block
def safe_string_repeat(text, count):
try:
## Attempt to repeat the string
result = text * count
return result
except TypeError as e:
print(f"Type Error: {e}")
return None
except ValueError as e:
print(f"Value Error: {e}")
return None
## Example usage
print(safe_string_repeat("LabEx", 3))
print(safe_string_repeat(123, 3)) ## Handles type error
Advanced Error Handling Strategies
Custom Exception Handling
class StringRepetitionError(Exception):
"""Custom exception for string repetition errors"""
def __init__(self, message, input_text, input_count):
self.message = message
self.input_text = input_text
self.input_count = input_count
super().__init__(self.message)
def advanced_string_repeat(text, count):
try:
if not isinstance(text, str):
raise StringRepetitionError(
"Invalid input type",
text,
count
)
if count < 0:
raise StringRepetitionError(
"Negative repetition count",
text,
count
)
return text * count
except StringRepetitionError as e:
print(f"Error: {e.message}")
print(f"Input Text: {e.input_text}")
print(f"Input Count: {e.input_count}")
return None
Error Handling Flow
graph TD
A[Input Received] --> B{Validate Input}
B -->|Valid Input| C[Perform Repetition]
B -->|Invalid Input| D[Raise Specific Exception]
D --> E[Catch Exception]
E --> F{Log Error}
F --> G[Return Default/None]
F --> H[Notify User]
Error Handling Strategies Comparison
Strategy |
Complexity |
Error Granularity |
Recommended Use |
Basic Try-Except |
Low |
Generic |
Simple scenarios |
Custom Exceptions |
Medium |
Specific |
Complex validation |
Logging Exceptions |
High |
Comprehensive |
Production environments |
Comprehensive Error Handling Example
import logging
## Configure logging
logging.basicConfig(
level=logging.ERROR,
format='%(asctime)s - %(levelname)s: %(message)s'
)
def robust_string_repeat(text, count, max_repeat=100):
try:
## Comprehensive input validation
if not isinstance(text, str):
raise TypeError("Text must be a string")
if not isinstance(count, int):
raise TypeError("Count must be an integer")
if count < 0:
raise ValueError("Repetition count cannot be negative")
if count > max_repeat:
raise ValueError(f"Cannot repeat more than {max_repeat} times")
return text * count
except (TypeError, ValueError) as e:
## Log the error
logging.error(f"Repetition Error: {e}")
## Provide a fallback
return f"Error: {str(e)}"
## Demonstration of error handling
print(robust_string_repeat("LabEx", 3))
print(robust_string_repeat(123, 3))
Best Practices for Error Handling
- Use specific exception types
- Provide informative error messages
- Log errors for debugging
- Implement graceful error recovery
- Avoid silent failures
Context Management
from contextlib import suppress
def safe_repeat_with_suppress(text, count):
## Suppress specific exceptions
with suppress(TypeError, ValueError):
return text * count
return None
## Example usage
print(safe_repeat_with_suppress("LabEx", 3))
print(safe_repeat_with_suppress(123, 3))
By implementing these error handling techniques, you can create more resilient and user-friendly string repetition functions that gracefully manage potential issues during execution.