当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Exception handling: what exception to raise

问题描述:

I am writing a python function that accepts certain parameters. I would like to make sure one of the parameter's value is a string of specific custom format. If it doesn't match the format I would like to raise an exception. Is it appropriate to raise one of the built-in exception and if yes which one?

I looked here: https://docs.python.org/3/library/exceptions.html# but couldn't pin down to a specific one.

网友答案:

As long as it provides a detailed and explicit error message, you can use a built-in one - ValueError, for example, looks logical here.

Another option would be to create a custom one:

class InvalidFormatError(ValueError):
    pass

There are relevant threads on SO that, I hope, would help you to decide which option to choose:

  • When to use custom exceptions vs. existing exceptions vs. generic exceptions
  • Is it OK to raise a built-in exception, but with a different message, in Python?
网友答案:

What you describe sounds like a ValueError:

Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

网友答案:

I would use ValueError:

Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

That it is raised by built in functions doesn't mean you can't raise it too.

分享给朋友:
您可能感兴趣的文章:
随机阅读: