try/ except 不捕获特定类型的异常

bge*_*hel 5 python google-app-engine python-2.7 webapp2

我试图捕获函数调用内引发的特定类型的异常。我将函数调用包含在 try/ except 块内,其中 except 块捕获抛出的特定异常。我仍然会获得该异常的系统失败堆栈跟踪,除非我还包含所有异常的常规捕获。在包含该块并检查所捕获的异常的类型时,我发现它正在捕获我想在第一个块中捕获的异常类型。不知道为什么会发生这种情况。

上下文:使用 webapp2 和 ndb 开发 Google 应用程序引擎应用程序。文件函数有一个init .py,它从 exceptions.py 导入所有异常

模拟代码和结构

utils/函数/Exceptions.py

"""
Custom exception types
"""

class InvalidParamsException(Exception):
def __init__(self, msg):
    self.msg = msg

def __str__(self):
    return repr(self.msg)
Run Code Online (Sandbox Code Playgroud)

模型/models.py

import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
import utils.functions as func
<-->
class ModelClass(ndb.Model):

    @classmethod
    def new(cls):
         <-->
         raise func.InvalidParamsException("Invalid Params to function!")
         <-->
Run Code Online (Sandbox Code Playgroud)

路线.py

import utils.functions as func
from models import ModelClass

class ModelClassHandler(webapp2.RequestHandler):
    def post(self):
        try:
            new_model = ModelClass.new()
        except func.InvalidParamsException as e:
            logging.debug("Caught the right Exception!!")
        except Exception as e:
            logging.debug(":(")
            logging.debug("EXCEPTION TYPE - %s"%str(type(e)))
Run Code Online (Sandbox Code Playgroud)

如果不包含第二个常规 except 块,我得到的输出是:

Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1535, in __call__
  rv = self.handle_exception(request, response, e)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1529, in __call__
  rv = self.router.dispatch(request, response)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
  return route.handler_adapter(request, response)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1102, in __call__
  return handler.dispatch()
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 572, in dispatch
  return self.handle_exception(e, self.app.debug)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 570, in dispatch
  return method(*args, **kwargs)
File "{{my_path}}/routes.py", line 58, in post
  new_model = ModelClass.new()
File "{{my_path}}/models/models.py", line 559, in new
  raise func.InvalidParamsException("Invalid Params to function!")
InvalidParamsException: 'Invalid Params to function!'
Run Code Online (Sandbox Code Playgroud)

如果我确实包含第二个块,我会优雅地传递路由/函数,并在日志中看到这一点:

DEBUG    2016-03-25 01:01:03,221 routes.py:66] EXCEPTION TYPE - <class 'utils.functions.exceptions.InvalidParamsException'>
Run Code Online (Sandbox Code Playgroud)

非常感谢帮助/指导!

小智 5

看来 Python 在当前命名空间中导入时引发了异常。我最好的证据是回溯的最后一行调用引发的异常“InvalidParamsException”而不是“somemodule.InvalidParamsException”。

因此,我建议解决命名空间冲突,将异常显式导入“routes.py”的命名空间:

from utils.functions.exceptions import InvalidParamsException

并通过现在解析的命名空间名称捕获异常:

except InvalidParamsException as inv_param_exp: <...>