How to exit early?

Bengt Richter bokr at
Mon Aug 12 15:56:27 EDT 2002

On Mon, 12 Aug 2002 16:51:32 GMT, Pete Shinners <pete at> wrote:

>brobbins333 at wrote:
>> The data input to my script may contain some that are special cases.
>> If so, I want to process these in a special function, then exit
>> without running the remainder of the script. What's the best way to do
>> this? I need something like the 'exitsub' command in Visual Basic, or
>> at least a way to jump to the end of the script and exit. Any
>> suggestions?
>two ways to do it. first is the "exit" function from the sys module.
>     exit([status])
>     Exit the interpreter by raising SystemExit(status).
>     If the status is omitted or None, it defaults to zero (i.e., success).
>     If the status is numeric, it will be used as the system exit status.
>     If it is another kind of object, it will be printed and the system
>     exit status will be one (i.e., failure).
>for example, you would use it like this,
>     import sys
>     sys.exit(10)
>you can also raise the SystemExit exception, which i often find is nice and 
>    raise SystemExit, "Exiting Early, whoops!"
You can also define your own exception, so that you can include some info and
catch it at the end to do something more with. E.g., (untested):

class BailAndDo(Exception):
    def __init__(self, info) : = info
   # do stuff
       # deeper nested
       if need_to_bail_out:
           raise BailAndDo(some_info_from_here)
except BailAndDo, e:

Bengt Richter

More information about the Python-list mailing list