1

If I have a function something like:

def foo(.. ):
  try:
    #something
    return_value = "bleh"
   except Exception,e:
     logging.error("exception " +e)
   return return_value

Does the above look ok? I mean, if I got the exception then return_value is never initialized.

What's a good way to handle exceptions in a function that has some return value?

7
  • You could consider returning None, but that may have unintended consequences on the calling function. Commented Aug 28, 2014 at 22:44
  • What would raise do in except part? Commented Aug 28, 2014 at 22:44
  • @Fraz yup, you can reraise the exception after logging it by using plain raise. Commented Aug 28, 2014 at 22:45
  • @alecxe: Yeah i think thats a better way than to return None?? though I guess it depends on use case.. Thanks Commented Aug 28, 2014 at 22:50
  • 1
    It all depends on what the function is intended to do. Suppose I want to read a config file but return a default if its not there or is corrupted. I would suppress the specific exceptions and return the default. An error in a function is not necessarily and error for the caller. It all depends on the design of that function. Commented Aug 29, 2014 at 0:39

1 Answer 1

2

You should return a False or something of that kind to tell the caller that some error has occurred. And then handle this return value in your caller, like if return is False do something else.

def foo(.. ):
    try:
        #something
        return_value = "bleh"
     except Exception,e:
        logging.error("exception " +e)
        return_value = False
     return return_value
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.