在python中处理ValueError的最佳方法是什么?

时间:2017-05-23 14:37:57

标签: python-3.x exception

我想检查我的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

1 个答案:

答案 0 :(得分:0)

如果您想拥有自定义和标准例外,您可以执行以下操作:

interface MyInterface {
    MyInterface getFirst();

    MyInterface[] getConstants();
}

enum MyEnum implements MyInterface {
    ONE, TWO, THREE;

    @Override
    public MyInterface getFirst() {
        return ONE;
    }

    @Override
    public MyInterface[] getConstants() {
        return new MyInterface[] {ONE, TWO, THREE};
    }
}

class MyClass {
   private MyInterface firstElement;

   MyClass (MyInterface enumType) {
      this.firstElement = enumType.getFirst();
   }
}
相关问题