Maybe you did not use exceptions before. I don't see what the problem could be, independently whether you use tkinter or not. It's exactly one path that the execution takes. Either no exception occurs, then the try
block is executed until its end (and the except
block skipped), or, an exception occurs, then the try
block is left before its end and the except
block gets executed.
For example, this output
success
Error: 'something bad happened'
will be produced by the following code
def check_something(bad):
if bad:
raise Exception('something bad happened')
pass
def run_xcheck(x):
try:
check_something(x)
print('Success')
except Exception as e:
print('Error: "{}"'.format(e))
run_xcheck(False)
run_xcheck(True)
For the sake of completeness, the following is (a kind of) proof that it works the same way together with tkinter. It takes into account the fact that the conversion of the input can fail if the user does not enter a number. In this case python raises the ValueError
exception, that you can catch as to display the specific error message:
import tkinter as tk
from tkinter import messagebox
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.master.title('Exception Test')
self.pack(padx=8, pady=8) # fill='both',
self.create_widgets()
def create_widgets(self):
self.content = tk.StringVar(value='1')
self.label = tk.Label(self,
text='Enter number:'
).pack(side='left')
self.entry = tk.Entry(self,
textvariable=self.content
).pack(side='left')
self.button = tk.Button(self,
text='Square it!',
command=self.square_pressed
).pack()
def square_pressed(self):
try:
i = int(self.content.get()) # conversion may fail
messagebox.showinfo(message='{}² → {}'.format(i, i**2))
except ValueError as e:
messagebox.showerror(message='error: "{}"'.format(e))
root = tk.Tk()
app = Application(master=root)
app.mainloop()
You should look up the actual exception class(es) that `pyodbc.connect' can raise to get the maximum amount of information. Maybe how to catch specific pyodbc error message could be worth reading.