Python Forum

Full Version: raise exception instead of return None
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i have a function that in a certain tested case returns None because calculations just didn't work out. instead, i'd rather have it raise an exception. what exception should it raise?
I would raise a ValueError
(Jul-18-2018, 08:51 PM)Skaperen Wrote: [ -> ]just didn't work out
Could you elaborate?

A ValueError would make sense if the function argument(s) were of "an inappropriate type" (according to the link). If that's what you mean by "just didn't work out" then it might apply, but it depends on why they didn't work out.
they "didn't work out" due to environmental conditions such as insuffient file space or not enough calculation information ... things out of control of the user that the calling script could have checked on.
Insufficient file space would be an IOError. Not enough calculation information sounds like a ValueError. If you know why the error is occurring, it's better to give that information with a more specific error type. If you don't know, you could give the catch all RuntimeError, or you could make your own exception:

class DidntWorkOutError(RuntimeError):
    pass