How to exit early?

Bengt Richter bokr at oz.net
Mon Aug 12 21:56:27 CEST 2002


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

>brobbins333 at shaw.ca 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 
>clean.
>
>    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) : self.info = info
...
try:
   ...
   # do stuff
   ...
       # deeper nested
       if need_to_bail_out:
           raise BailAndDo(some_info_from_here)
   ...
except BailAndDo, e:
   do_something_with_bailout_info(e.info)

Regards,
Bengt Richter



More information about the Python-list mailing list