Skip to main content
 首页 » 编程设计

python之很多 try/except 语句

2025年05月04日15qq号

在我的 views.py 中有以下代码:

# Exceptions for GET requests 
try: 
    page = int(request.GET["page"]) 
except Exception: 
    page = 1 
try: 
    price_from = request.GET["price_from"] 
except Exception: 
    price_from = -5 
try: 
    price_to = request.GET["price_to"] 
except Exception: 
    price_to = "all" 
# ... 
# Another 10+ try/except statements for now, but more will come 

我需要从 GET 请求中获取变量,这些变量可以但不必在链接中声明。有没有更干净/更好的方法来做到这一点,或者在代码中有大量的 try/except 是正常的?谢谢。

请您参考如下方法:

只需使用 get 方法并提供默认值:

try: 
    page = int(request.GET.get("page", 1)) 
except ValueError: 
    page = 1 
price_from = request.GET.get("price_from", -5) 
price_to = request.GET.get("price_to", "all") 

即使您确实需要处理异常,也请尝试只处理您期望的异常,否则其他错误可能会被忽视。