```python
# Python异常处理实用技巧
## 1. 基础异常处理结构
```python
try:
# 可能引发异常的代码
result = 10 / 0
except ZeroDivisionError as e:
# 处理特定异常
print(f除零错误: {e})
except (ValueError, TypeError) as e:
# 处理多个异常
print(f值或类型错误: {e})
except Exception as e:
# 捕获所有其他异常
print(f未知错误: {e})
else:
# 如果没有异常发生
print(操作成功)
finally:
# 无论是否发生异常都会执行
print(清理操作)
```
## 2. 自定义异常类
```python
class CustomError(Exception):
自定义异常基类
def __init__(self, message, error_code=None):
self.message = message
self.error_code = error_code
super().__init__(self.message)
class ValidationError(CustomError):
数据验证异常
pass
def validate_age(age):
if age < 0 or age > 150:
raise ValidationError(年龄必须在0-150之间, INVALID_AGE)
try:
validate_age(-5)
except ValidationError as e:
print(f验证错误: {e.message} (代码: {e.error_code}))
```
## 3. 上下文管理器处理资源
```python
from contextlib import contextmanager
@contextmanager
def database_connection(connection_string):
connection = None
try:
connection = create_connection(connection_string)
yield connection
except DatabaseError as e:
print(f数据库错误: {e})
raise
finally:
if connection:
connection.close()
# 使用示例
with database_connection(db://localhost/mydb) as conn:
conn.execute_query(SELECT FROM users)
```
## 4. 异常链与重新抛出
```python
def process_data(data):
try:
return int(data)
except ValueError as e:
raise ProcessingError(f无法处理数据: {data}) from e
class ProcessingError(Exception):
pass
try:
process_data(abc)
except ProcessingError as e:
print(f处理错误: {e})
print(f原始异常: {e.__cause__})
```
## 5. 使用装饰器统一异常处理
```python
def handle_exceptions(func):
def wrapper(args, kwargs):
try:
return func(args, kwargs)
except ValueError as e:
print(f值错误: {e})
return None
except Exception as e:
print(f未预期错误: {e})
return None
return wrapper
@handle_exceptions
def risky_operation(x, y):
return x / y
result = risky_operation(10, 0) # 安全执行
```
## 6. 日志记录与异常处理结合
```python
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def safe_file_operation(filename):
try:
with open(filename, 'r') as file:
return file.read()
except FileNotFoundError:
logger.warning(f文件不存在: {filename})
return
except PermissionError:
logger.error(f没有权限访问文件: {filename})
raise
except Exception as e:
logger.exception(f读取文件时发生未知错误: {e})
raise
```
## 7. 使用else子句优化代码结构
```python
def process_user_data(user_data):
try:
data = json.loads(user_data)
except json.JSONDecodeError as e:
print(fJSON解析错误: {e})
return None
else:
# 只有在没有异常时才执行
if validate_user_data(data):
return create_user(data)
else:
print(数据验证失败)
return None
```
## 8. 异常处理最佳实践
```python
# 好的实践:具体异常处理
def good_practice():
try:
value = int(123)
except ValueError as e:
handle_error(e)
# 不好的实践:过于宽泛的异常捕获
def bad_practice():
try:
value = int(123)
except: # 捕获所有异常,不推荐
pass
# 使用异常层次结构
def handle_api_call():
try:
response = requests.get(https://api.example.com/data)
response.raise_for_status()
return response.json()
except requests.HTTPError as e:
if e.response.status_code == 404:
print(资源未找到)
elif e.response.status_code == 500:
print(服务器错误)
else:
print(fHTTP错误: {e})
except requests.ConnectionError:
print(网络连接错误)
except requests.Timeout:
print(请求超时)
```
## 9. 使用functools.singledispatch处理不同类型异常
```python
from functools import singledispatch
@singledispatch
def handle_error(exc):
默认异常处理器
print(f未处理的异常类型: {type(exc).__name__}: {exc})
@handle_error.register
def _(exc: ValueError):
print(f值错误处理: {exc})
@handle_error.register
def _(exc: TypeError):
print(f类型错误处理: {exc})
# 使用示例
try:
# 可能抛出异常的代码
pass
except Exception as e:
handle_error(e)
```
这些技巧可以帮助你编写更健壮、可维护的Python代码,有效处理各种异常情况。
299

被折叠的 条评论
为什么被折叠?



