【问题标题】:What is the best way to handle ValueError in python?在 python 中处理 ValueError 的最佳方法是什么?
【发布时间】:2017-05-23 14:37:57
【问题描述】:

我想检查我的 python 应用程序中的类型错误。 下面这种方式捕捉ValueError是否正确?

async def find_video_by_id(request):
    try:
        id = int(request.query['id'])
        ...
    except ValueError:
        exception_message = "Incorrect type of video id was specified."
        logger.exception(exception_message)
        raven_client.captureException(exception_message)
        raise ValueError(exception_message)
    except Exception as ex:
        logger.exception("find_video_by_id")
        raven_client.captureException()
        raise ex

【问题讨论】:

  • 对不起,只是为了理解,为什么在异常中时要引发异常?我在较小的代码上尝试过,但这样做时遇到了问题。

标签: python-3.x exception


【解决方案1】:

如果你想有自定义和标准的例外,你可以这样做:

# Custom Exception
class MyError(Exception):
    pass

try:
    id = int(request.query['id']) #raise ValueError automatically if string cannot be parsed
    if id == 'foo': # just to show how to raise a custom Exception
        raise MyError
    else:
        bar()
except ValueError:
     exception_message = "Incorrect type of video id was specified."
     logger.exception(exception_message)
     raven_client.captureException(exception_message)
except MyError:
     exception_message = "Incorrect stuff."
     logger.exception(exception_message)
     raven_client.captureException(exception_message)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    • 2011-09-16
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    相关资源
    最近更新 更多