How to quit Python function, throwing error statement without quitting Python interpreter

64,526

You have two options (at least).

Using a return statement:

def do_something(parameter):
    if parameter > 100:
        # display error message if necessary
        return  # 'exit' function and return to caller
    # rest of the code

You can also return soemthing passing the something value back to the caller. This can be used to provide a status code for instance (e.g. 0: success, 1: error).

Or a better approach is to raise an exception:

def do_something(parameter):
    if parameter > 100:
        raise ValueError('Parameter should...')
    # rest of the code

try:
    do_something(101)
except ValueError, e:
    # display error message if necessary e.g. print str(e)

See exceptions in the Python manual.

There are built-in exception classes (like ValueError above). You can also define your own as follows:

class ParameterError(Exception):
    pass

You can also add additional code to your custom exception classes to process parameters, display custom error messages, etc...

The built-in exceptions are listed here.

Share:
64,526

Related videos on Youtube

Gyan Veda
Author by

Gyan Veda

Hello. I am #SOreadytohelp!

Updated on July 21, 2022

Comments

  • Gyan Veda
    Gyan Veda almost 2 years

    I'm new to Python and struggling with handling self-defined errors. When my code spots the error, I want it to throw an error in red font and take me back to the Python terminal without killing Python.

    I came across sys.exit() looking for an answer, but it quits Python completely. Do you know of an alternative that throws back an error in red font and takes me back to the terminal?

    This is what I have so far.

    import sys
    def do_something(parameter):
        if parameter > 100:
            # quit the function and any function(s) that may have called it
            sys.exit('Your parameter should not be greater than 100!')
        else:
            # otherwise, carry on with the rest of the code
    

    Please let me know if I'm not clear and I'll be happy to provide more details. Thank you all in advance!

    • anon582847382
      anon582847382 about 10 years
      See if print(error_msg) and then exit(1) works. I'm on a mobile device at the moment so I'm not sure!
  • Admin
    Admin about 10 years
    Of course, this doesn't work if the code in between does try: ... except Exception: ...
  • Daniel Roseman
    Daniel Roseman about 10 years
    @delnan but why would anyone ever do anything like that :-)
  • Admin
    Admin about 10 years
    Perhaps out of ignorance (I see many beginners just doing except:), perhaps because they really want to catch all exception out of some misguided sense of "reliability" (sometimes seen in intermediate programmers), perhaps because catching (almost) all exceptions really is the correct thing to do at this point, e.g. you're running arbitrary code (e.g. a hook) and need to be robust against errors in that code.
  • Admin
    Admin about 10 years
    return only returns to the caller, which is not necessarily the REPL. As for exceptions, they can (and frequently are) caught.
  • Admin
    Admin about 10 years
    Huh? The answer still is "return or raise an exception", and my objections to both still stand.
  • isedev
    isedev about 10 years
    I think you are interpreting the question far beyond the OP's intent.