簡體   English   中英

嘗試/除了沒有捕獲特定類型的異常

[英]try/except not catching a specific type of exception

我正在嘗試捕獲函數調用中拋出的特定類型的異常。 我在try / except塊中包含了函數調用,其中except塊捕獲了拋出的特定異常。 我仍然得到該異常的系統失敗堆棧跟蹤,除非我還包含所有異常的常規catch。 在包含該塊並檢查被捕獲的異常的類型時,我看到它正在捕獲我想要在第一個塊中捕獲的異常類型。 不知道為什么會這樣。

上下文:使用webapp2和ndb處理谷歌應用引擎應用。 文件函數有一個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)

車型/ 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!")
         <-->

routes.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)))

如果我不包括第二個常規除了塊,我得到的輸出是:

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!'

如果我確實包含第二個塊,我會優雅地傳遞路由/函數,並在日志中看到:

DEBUG    2016-03-25 01:01:03,221 routes.py:66] EXCEPTION TYPE - <class 'utils.functions.exceptions.InvalidParamsException'>

幫助/指導非常感謝!!

看起來Python引發了在當前命名空間中導入的異常。 我最好的evicende是事實,回溯的最后一行調用引發的異常“InvalidParamsException”而不是“somemodule.InvalidParamsException”。

因此,我建議解決名稱空間沖突,將異常明確地導入到“routes.py”的命名空間中:

from utils.functions.exceptions import InvalidParamsException

並通過其現在解析的命名空間名稱捕獲異常:

except InvalidParamsException as inv_param_exp: <...>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM