Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Exceptions

Name: newfag 2012-04-22 10:59

What is the best way of dealing with invalid argument?
Throw an exception or return null?

Lets have an example. I was writing this function that
creates date objects for dates in between 2000-01-01 and
2999-12-31

Looks like this:
<code>
def createDate(date):
    try:
        y, m, d = date
        if(y < 0): return None
        if(y < 2000): y += 2000
        if(y > 2999): return None
        return datetime.date(y, m, d)
    except ValueError:
        return None
</code>

What should i do here? Should i just let the ValueError
error propagate up the stack, maybe throw my own ValueError exceptions in stead of returning None or should i
invent my own exception and throw that instead of ValueError,
or just leave it as it is?


What would you do?

>in b4 "dat shitty language"

Name: Anonymous 2012-04-22 14:37

>>6
if you have a piece of code where failure is expected then it shouldn't be an exception, user input is not reliable input so it should be expected to be malformed, only use exception in really exceptional circunstances

That's not what "exception" means (or should mean) in this case. Just because we're all expected to die someday doesn't mean that your own death isn't an exceptional circumstance for you.

As a rule, exceptions should be raised whenever the function could not do what it says on the tin. In practice, this means you have to think clearly about what to put on the tin. For instance, ''.toUpper() would not be changing any cases, but for a good definition of toUpper, that is not exceptional behavior.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List