1. Core syntax analysis
1.1 Basic syntax form
raise [Exception type[(parameter)]]
Usage instructions:
- Only exists in exception handling blocks (
except
orfinally
)internal - Automatically rethrow the currently caught exception
- Keep original exception stack information
1.2 Complete syntax structure
raise [Exception type[(parameter)]] [from reason]
2. Basic usage scenarios
2.1 Triggering built-in exception
# Parameter verification scenariodef calculate_square(n): if not isinstance(n, (int, float)): raise TypeError("Numerical type must be passed in") return n ** 2 # Call examplecalculate_square("5") # trigger TypeError
3. Advanced usage techniques
3.1 Exception Chaining
import json try: config = (open('')) except FileNotFoundError as fnf_error: raise RuntimeError("Profile loading failed") from fnf_error # Error output shows association# RuntimeError: Configuration file failed to load# The above exception was the direct cause of...
3.2 Custom exception triggers python
class NetworkTimeout(Exception): """Custom network timeout exception""" def __init__(self, host, timeout): = host = timeout super().__init__(f"connect {host} time out({timeout}s)") # Trigger custom exceptionif response_time > 30: raise NetworkTimeout("", 30)
4. Detailed explanation of special forms
4.1 No exception type throw
def deprecated_feature(): raise "This feature is deprecated" # ❌ Error! An Exception instance must be thrown # The correct way to do itdef deprecated_feature(): raise DeprecationWarning("This feature is deprecated")
4.2 Exception parameter passing
try: raise ValueError("Invalid input", 404, {"detail": "Illegal ID"}) except ValueError as e: print() # ('Invalid input', 404, {'detail': 'ID is illegal'})
5. Common usage modes
5.1 Defensive programming
def divide(a, b): if b == 0: raise ZeroDivisionError("The divisor cannot be zero") return a / b
5.2 API Error Handling
def fetch_data(url): response = (url) if 400 <= response.status_code < 500: raise ClientError(response.status_code, ) elif response.status_code >= 500: raise ServerError(response.status_code) return ()
6. Best Practice Guide
6.1 Principle of exception type selection
Error scenario | Recommended exception types |
---|---|
Parameter type error | TypeError |
Invalid parameter value | ValueError |
File operation error | IOError |
Business rules violations | Custom exceptions |
6.2 Exception message specification
# Not recommendedraise ValueError("Error occurred") # Recommended formatraise ValueError(f"parameter {param} Value of {value} Exceeded valid range(Allowed range:{min}~{max})")
7. Things to note
from
Parameter usage
# Show the original exception causeraise ParsingError from original_error
Performance considerations
- Avoid frequent throwing of exceptions in loops
- Exception processing time is determined by conditional
10-100
Double
Debugging Assistance
# Print the full stackimport traceback try: risky_call() except: traceback.print_exc() raise # Re-throw
8. Comprehensive application examples
8.1 Data verification chain
def validate_user(user): if not ('username'): raise ValueError("Username Required") if len(user['password']) < 8: raise SecurityError("Password at least 8 digits") if not (r"[^@]+@[^@]+\.[^@]+", user['email']): raise FormatError("Invalid mailbox format") return True
8.2 Context Manager
class Transaction: def __enter__(self): if not .is_valid(): raise ConnectionError("Database connection failed") return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type: () raise TransactionError("Transaction execution failed") from exc_val ()
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.