24

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!

Gyan Veda
  • 6,309
  • 11
  • 41
  • 66

2 Answers2

42

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.

isedev
  • 18,848
  • 3
  • 60
  • 59
  • `return` only returns to the caller, which is not necessarily the REPL. As for exceptions, they can (and frequently are) caught. –  Mar 02 '14 at 19:34
  • Huh? The answer still is "`return` or raise an exception", and my objections to both still stand. –  Mar 02 '14 at 19:37
  • I think you are interpreting the question far beyond the OP's intent. – isedev Mar 02 '14 at 19:51
0

Define a custom exception, and raise it.

class MyError(Exception):
    pass

...

if parameter > 100:
    # quit the function and any function(s) that may have called it
    raise MyError('Your parameter should not be greater than 100!')

(although actually, now I think about it, you could just use a built-in exception: ValueError would seem appropriate).

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Of course, this doesn't work if the code in between does `try: ... except Exception: ...` –  Mar 02 '14 at 19:31
  • @delnan but why would anyone ever do anything like that :-) – Daniel Roseman Mar 02 '14 at 19:31
  • 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. –  Mar 02 '14 at 19:33