Python Forum
How to exit after a try exception?
Thread Rating:
  • 3 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to exit after a try exception?
#1
I've read so much about try and exception but none tell how to exit the program gracefully and not continue the rest of the code.  For example:

try:
    result = x / y
except ZeroDivisionError:
    print "division by zero!"
    (How do I exit the program from here?)
    (Alternatively, how do I continue the program on a different path from here?)
else:
    print "result is", result
(continue normal execution from here)
So if there is a divide by zero error, how does one exit the program from that point?
Alternatively, is there a way to jump to a different label in the program to continue execution on a different path like in Basic?

Newbie learning Python 3.6
Reply
#2
I'm not sure what you mean by "exit the program." In one sense, if you want to exit the program at that point, you don't put in a try/except block. The ZeroDivisionError will exit the program. If this was part of a function or method, you could put a return statement there to exit the function/method. You could use sys.exit(), but that just raises a different exception, so it seems kind of pointless.

If you want to continue with the program, you just don't do anything. Your example will continue execution after the else block. I'm not sure what you mean by "continue on a different path." If you want completely different execution of the entire program after the ZeroDivision error, one path needs to be in the except block and the other in the else block. I mean, you could call different functions from those places, so the code is elsewhere, but the whole rest of the program would have to be in those two blocks.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Hello!

The sys module has what you want.

 
import sys

sys.exit()
sys.exit("error message here for instance") # if something goes wrong
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#4
I would recommend to omit the 'else'.

try:
    result = x / y
    print("result is", result)
except ZeroDivisionError:
    print("division by zero!")
If you predefine a 'result', you can also do:
result = None
x = 4
y = 0

try:
    result = x / y
except ZeroDivisionError:
    print("division by zero!")
print("result is", result)
If you do:

x = 4
y = 0
try:
    print("x is ", x)
    print("y is", y)
    result = x / y
    print("result is", result)
except ZeroDivisionError:
    print("division by zero!")
then you will see that the both first printed lines appear. During execution, everything is still fine there. Python only 'leaps' to the except part for further execution if it finds something going wrong. Everyting that can be done without the 'output' of the try-statement will be done when execution reaches is.


Oh, one thing: you are sure you use python 3? Your print-statements look like being python 2?
Reply
#5
You a function,then return will exit out of function.
def foo(x, y):
   try:
       result = x / y
       return result
   except ZeroDivisionError:
       return("division by zero!")
Test:
>>> x = 4
>>> y = 6
>>> foo(x, y)
0.6666666666666666
>>> y = 3
>>> foo(x, y)
1.3333333333333333
>>> y = 0
>>> foo(x, y)
'division by zero!'
Reply
#6
(Mar-04-2017, 01:47 AM)ichabod801 Wrote: I'm not sure what you mean by "exit the program." In one sense, if you want to exit the program at that point, you don't put in a try/except block. The ZeroDivisionError will exit the program. If this was part of a function or method, you could put a return statement there to exit the function/method. You could use sys.exit(), but that just raises a different exception, so it seems kind of pointless.

If you want to continue with the program, you just don't do anything. Your example will continue execution after the else block. I'm not sure what you mean by "continue on a different path." If you want completely different execution of the entire program after the ZeroDivision error, one path needs to be in the except block and the other in the else block. I mean, you could call different functions from those places, so the code is elsewhere, but the whole rest of the program would have to be in those two blocks.

Hi ichabod801,

My intent is to compile my program to a .exe using cx_freeze or py2exe.  I will be using Tkinter to create a GUI for the user.  If Python gets a "file not found" or other error, I want to display a message to let the user know what happened.  Then when the user clicks OK, exit my program.  I didn't know how to exit the code in "except:", after I displayed the error message, to terminate my program gracefully without the traceback causing an exit error or if it would even be visible to the user in a .exe program.  (I'm a total newbie writing my first Python program, though I've programmed in Basic, C and assembler about 20 years ago.)

Alternatively, I wanted to give the user a way to go back to the start of my program and redo his inputs without the exception error terminating and exiting my program.  I want to learn how to do that too.

The divide by zero was just an example I happened to copy from the web.  I see now that it was in Python 2 instead of Python 3.  I'm using Python 3.6.

EDIT:  "The ZeroDivisionError will exit the program."
BTW, I just ran my program again.  After the "except:" error, the code prints "Image not found" in the console.  Then the program just continues and displays the user GUI anyway.  It does not exit the program. 

try:
    imageEx = PhotoImage(file = 'Lisa.gif')
    Label(leftFrame, image=imageEx).grid(row=2, column=0, padx=10, pady=2)
except:
    print("Image not found")
Thanks for the help,
Raptor88

(Mar-04-2017, 04:14 AM)wavic Wrote: Hello!

The sys module has what you want.

 
import sys

sys.exit()
sys.exit("error message here for instance") # if something goes wrong

Hi wavic,

Thanks for posting the code.  It's very helpful to learn how to exit a Python program. 

I had looked for "exit" in the index of the Python books I have and it's not even listed.  One book does have "SytemExit" in the index but how would a newbie know the keywords to search for?  Python book authors can spend so much time writing their books but so little time in making their index capable for newbies who don't know the proper keywords.

Thanks again,
Raptor88

(Mar-04-2017, 08:44 AM)merlem Wrote: I would recommend to omit the 'else'.
.... snip ....
Oh, one thing: you are sure you use python 3? Your print-statements look like being python 2?

Thank you for your input.  I am using Python 3.6 but inadvertently copied a sample code from Python 2.  Please see my response to Ichabod808 for what I'm trying to do.

(Mar-04-2017, 10:13 AM)snippsat Wrote: You a function,then return will exit out of function.
.... snip ....

Thank you for your input.  Please see my response to Ichabod808 for what I'm trying to do.
Reply
#7
When you have a GUI or web-application you have to be spare with error message to user.
It can be okay to give message like "file not found" and "division error" as they are clear messages.
GUI shall not shut down on error like these,that's just bad and annoying for users.
"exe" is just a freezed version of your python program so they should work the same.

Logging is good way to get error so you can get it see/fix if there is a problem,
and hide it from user so they only get useful info.
Look at Good logging practice in Python

Eg of logging exception:
import logging
 
logging.basicConfig(filename='my.log', filemode='w', level=logging.DEBUG)
try:
    n = 1 / 0
except Exception as error:
    logging.exception('msg')
my.log:
Output:
ERROR:root:msg Traceback (most recent call last):   File "log1.py", line 5, in <module>     n = 1/0 ZeroDivisionError: division by zero
Reply
#8
It's OK to print out the error messages or any kind of useful information during a running program. Sometimes things go wrong and one may want to run the program from a terminal to see this output which doesn't appear in a GUI application.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#9
(Mar-04-2017, 07:41 PM)Raptor88 Wrote: I had looked for "exit" in the index of the Python books I have and it's not even listed.  One book does have "SytemExit" in the index but how would a newbie know the keywords to search for?  Python book authors can spend so much time writing their books but so little time in making their index capable for newbies who don't know the proper keywords.
It's in the sys module. Check out the sys documentation.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#10
(Mar-04-2017, 08:57 PM)snippsat Wrote: When you have a GUI or web-application you have to be spare with error message to user.
It can be okay to give message like "file not found" and "division error" as they are clear messages.
GUI shall not shut down on error like these,that's just bad and annoying for users.
"exe" is just a freezed version of your python program so they should work the same.

Logging is good way to get error so you can get it see/fix if there is a problem,
and hide it from user so they only get useful info.
Look at Good logging practice in Python
... snip ...

Thanks for the logging tip. My early programs will be simple so it will be a while before I need to do logging. But I will remember your post and refer back to it when the time comes.

(Mar-04-2017, 09:20 PM)wavic Wrote: It's OK to print out the error messages or any kind of useful information during a running program. Sometimes things go wrong and one may want to run the program from a terminal to see this output which doesn't appear in a GUI application.

Got it.  Thanks.

(Mar-04-2017, 10:35 PM)ichabod801 Wrote: It's in the sys module. Check out the sys documentation.

With wavic's tip about "sys.exit", I think I can exit my program OK with the brief test I did. A more through test of informing the user of the error before exiting will be the next step.

Thinking about how to allow the user to go back to the beginning of my program after an "except" error, I think the way to do that is to put everything in a while loop. If a "file not found" error occurs, let the user know and then break back to the beginning of the while loop.

If that's not the best way, then anyone, do let me know.

Thanks,
Raptor88
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python difference between sys.exit and exit() mg24 1 1,764 Nov-12-2022, 01:37 PM
Last Post: deanhystad
  name of exception for exit() Skaperen 2 2,366 May-24-2019, 07:07 PM
Last Post: Skaperen
  During handling of the above exception, another exception occurred Skaperen 7 26,728 Dec-21-2018, 10:58 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020