Skip to main content
 首页 » 编程设计

python之何时在 GAE 中使用 try/except block

2025年05月04日11unruledboy

我最近开始使用 GAE 和 Python 开发我的第一个 Web 应用程序,这很有趣。

我一直遇到的一个问题是在我不希望出现异常时出现异常(因为我是网络应用程序的新手)。我想:

  1. 防止用户看到异常
  2. 正确处理异常,以免它们破坏我的应用

我应该在每次调用 put 和 get 时都放置一个 try/except block 吗? 我应该用 try/except 包装哪些其他操作可能会失败?

请您参考如下方法:

您可以在请求处理程序上创建一个名为 handle_exception 的方法来处理意外情况。

webapp 框架会在遇到问题时自动调用它

class YourHandler(webapp.RequestHandler): 
 
    def handle_exception(self, exception, mode): 
        # run the default exception handling 
        webapp.RequestHandler.handle_exception(self,exception, mode) 
        # note the error in the log 
        logging.error("Something bad happend: %s" % str(exception)) 
        # tell your users a friendly message 
        self.response.out.write("Sorry lovely users, something went wrong")