Aleksandar Beat
Aleksandar Beat

Reputation: 201

Stop program from running after try / except python

I made a program that takes values from treeview and calculate something when button is pressed. I put try / except statement inside that function.

def SumAll():
    try:
       #do something (calculate)

    except ValueError:

        Error=messagebox.showinfo("Enter proper values")
        pass

The problem is, program keeps running when messagebox.showinfo appears, and it gives the ValueError. How can I fix that, and how can I put more than one error exception (IndexError, etc)?

Upvotes: 0

Views: 9035

Answers (2)

Patrick Artner
Patrick Artner

Reputation: 51643

You can catch multiples by:

try:
    k = input().split()[2]
    i = int(k[0])
except (IndexError, ValueError) as e:
    print(e)  # list index error: 'Hello World', Value error: 'Hello World Tata'
else:
    print("no error")

this will guard against inputs that split to less then 3 items '5 a' as well as against int conversion errors: 'Hello World Is A Cool Thing' (`'Is'`` is not an integer).

Use How to debug small programs (#1) to debug through your real program, the error you get above this except is caught. You probably get a resulting error somewhere else because somethings not right with the return of your function.

Upvotes: 0

Michal Charemza
Michal Charemza

Reputation: 27012

You can re-raise the exception, and if the exception reaches the top of the stack, the program will exit

try:
    #do something (calculate)
except ValueError:
    Error=messagebox.showinfo("Enter proper values")
    raise

Or you can manually call sys.exit

import sys

try:
    #do something (calculate)
except ValueError:
    Error=messagebox.showinfo("Enter proper values")
    sys.exit(1)

To catch more than on in the same handler, you can do something like

try:
    #do something (calculate)
except (IndexError, ValueError):
    Error=messagebox.showinfo("Enter proper values")
    raise

or if you want different handlers you can have

try:
    #do something (calculate)
except IndexError:
    Error=messagebox.showinfo("Some message")
    raise
except ValueError:
    Error=messagebox.showinfo("Enter proper values")
    raise

Upvotes: 1

Related Questions