简体   繁体   中英

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM