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-24 19:19

>>1
The correct solution is to assert() or abort(). If an API is being misused, you should fail as quickly and as loudly as possible so that the programmer who fucked it up notices and can fix it (hopefully before he even commits his code.)

Unfortunately many languages don't let you do this, so throwing an exception is your best bet.

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