'How do I execute first my custom error message before the first Traceback?

I made a program with restrictions with Tkinter and I created a custom error message wherein if the conditions for the restriction is met, then an error message box would pop up.

Now, my problem is that the message box only pops up after terminating my program, it doesn't get executed while the program is still open, here's my code.

try:
    None

except:
    raise SyntaxError(messagebox.showerror('Error', 'Error message')

This is the output:

Exception in Tkinter callback Traceback (most recent call last):
File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\tkinter_init_.py", line 1921, in call return self.func(*args) File "C:\Users\user1\PycharmProjects\Python Program\main.py", line 53, in command=lambda: equal(), relief=FLAT, borderwidth=1) File "C:\Users\user1\PycharmProjects\Python Porgram\main.py", line 32, in equal result = str(eval(expression)) File "", line 1 */ ^ SyntaxError: invalid syntax Traceback (most recent call last): File "C:\Users\user1\PycharmProjects\Python Program\main.py", line 171, in raise SyntaxError(messagebox.showerror('Error', 'You cannot bundle two or more operations together.')) SyntaxError: ok

Process finished with exit code 1



Solution 1:[1]

try:
    # Anything you want to do.
    # If in this block a SyntaxError happens, you'll
    # catch it with the line below and do whatever you want
    # instead of raising and actual exception.
except SyntaxError:
    messagebox.showerror('Error', 'Error message')

If you don't know what kinds of exceptions can be raised within your try, you can replace the except SyntaxError: with except:. But I recommend you to be explicit here with the exceptions. As exceptions arises, append the specific ones.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1