-2
try:
 x="blaabla"
 y="nnlfa"   
 if x!=y:
        sys.exit()
    else:
        print("Error!")
except Exception:
    print(Exception)

I'm not asking about why it is throwing an error. I know that it raises exceptions.SystemExit. I was wondering if there was another way to exit?

kragor
  • 105
  • 2
  • 11
  • 5
    What's wrong with using `sys.exit`? If we don't know why you need a different solution, we can't suggest one that's going to work for you. – Morgan Thrapp Jul 21 '16 at 17:54
  • 2
    I don't understand the down votes, its a legitimate question. If you want to avoid object deletion processing you can use `os._exit`. – tdelaney Jul 21 '16 at 18:10
  • hello @Morgan Thrapp.come on man.thats not working.this is the reason i want an another solution.I've made changes in question.please help me to sort this out. – kragor Jul 21 '16 at 18:15
  • 2
    I still don't understand what you need. Do you just need to exit your script? If so, what's wrong with `sys.exit`? Do you need to skip the normal exit routine? Then use @tdelaney answer. If it's something else, you need to clarify what you need. – Morgan Thrapp Jul 21 '16 at 18:17

2 Answers2

3

os._exit() will do a low level process exit without SystemExit or normal python exit processing.

tdelaney
  • 73,364
  • 6
  • 83
  • 116
1

Some questions like that should really be accompanied by the real intention behind the code. The reason is that some problems should be solved completely differently. In the body of the script, the return can be used to quit the script. From another point of view, you can just remember the situation in a variable and implement the wanted behaviour after the try/except construct. Or your except may test more explicit kind of an exception.

The code below shows one variation with the variable. The variable is assigned a function (the assigned function is not called here). The function is called (via the variable) only after the try/except:

#!python3

import sys

def do_nothing():
    print('Doing nothing.')

def my_exit():
    print('sys.exit() to be called')
    sys.exit()    

fn = do_nothing     # Notice that it is not called. The function is just
                    # given another name.

try:
    x = "blaabla"
    y = "nnlfa"   
    if x != y:
        fn = my_exit    # Here a different function is given the name fn.
                        # You can directly assign fn = sys.exit; the my_exit
                        # just adds the print to visualize.
    else:
        print("Error!")
except Exception:
    print(Exception)

# Now the function is to be called. Or it is equivalent to calling do_nothing(),
# or it is equivalent to calling my_exit(). 
fn()    
pepr
  • 20,112
  • 15
  • 76
  • 139