alwbtc
alwbtc

Reputation: 29465

Python functions return 1 when there is an exception

Could you please explain why does the followin function return "1" when there is an exception? What is the purpose of returning "1"?

def initialize():
    """
    Starting point for the program.
    """
    try:
        go = Car()
        print "Instance of Car created"
    except KeyboardInterrupt:
        return 1

Upvotes: 2

Views: 4254

Answers (2)

Swiss
Swiss

Reputation: 5829

It's a fairly common idiom in C to return a non-zero value in case of an error.

My hunch here is that the person who created this function was used to programming in C and unfamiliar with exception handling. It's impossible to tell without a larger code sample, but if I'm right, then there is probably some sort of error handling present where this function is called in the case that this function returns 1, or a non-zero value.

If this is the case, a more proper way to use the exception would be to either use raise to pass the exception upward to be handled else where, or handle the exception right there in the function.

Upvotes: 4

BrainStorm
BrainStorm

Reputation: 2046

In my opinion there's no need to do this, only if the Car() constructor takes too long and you want to deal with it once initialize() returns.

Upvotes: 0

Related Questions