Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I exit program in try/except?

I have this try/except code:

document = raw_input ('Your document name is ')  try:     with open(document, 'r') as a:         for element in a:            print element  except:     print document, 'does not exist' 

How do I exit the program after I print "[filename] does not exist"? break and pass obviously don't work, and I don't want to have any crashing errors, so sys.exit is not an option.

Please ignore the try part - it's just a dummy.

like image 680
rudster Avatar asked Apr 15 '12 22:04

rudster


People also ask

How do I get out of TRY except?

Use an else clause right after the try-except block. The else clause will get hit only if no exception is thrown. The else statement should always precede the except blocks. In else blocks, you can add code which you wish to run when no errors occurred.

How do you end a program in TRY except Python?

finally ..." in Python. In Python, try and except are used to handle exceptions (= errors detected during execution). With try and except , even if an exception occurs, the process continues without terminating. You can use else and finally to set the ending process.

Does try except stop the program?

The try… except block is completed and the program will proceed. However, if an exception is raised in the try clause, Python will stop executing any more code in that clause, and pass the exception to the except clause to see if this particular error is handled there.

What is exit () in Python?

exit() method is used to terminate the process with the specified status. We can use this method without flushing buffers or calling any cleanup handlers. Example: import os for i in range(5): if i == 3: print(exit) os._exit(0) print(i) After writing the above code (python os.


2 Answers

Use the sys.exit:

import sys  try:     # do something except Exception, e:     print >> sys.stderr, "does not exist"     print >> sys.stderr, "Exception: %s" % str(e)     sys.exit(1) 

A good practice is to print the Exception that occured so you can debug afterwards.

You can also print the stacktrace with the traceback module.

Note that the int you return in sys.exit will be the return code of your program. To see what exit code your program returned (which will give you information about what happens and can be automated), you can do:

echo $? 
like image 91
Charles Menguy Avatar answered Oct 02 '22 13:10

Charles Menguy


Using

sys.exit(1) 

is not a crashing error, it's a perfectly normal way to exit a program. The exit code of 1 is a convention that means something went wrong (you would return 0 in the case of a successful run).

like image 29
Greg Hewgill Avatar answered Oct 02 '22 14:10

Greg Hewgill