2

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.

user3885927
  • 3,363
  • 2
  • 22
  • 42

3 Answers3

4

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:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 1
    If you create a custom exception class, it should probably still be a subclass of ValueError for this use case (not just a direct subclass of `Exception`). – BrenBarn Sep 03 '14 at 21:47
3

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.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
2

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.

RedGlyph
  • 11,309
  • 6
  • 37
  • 49
Michael Buckley
  • 591
  • 4
  • 14