Simple Approach to Error Handling in Python (Application in GUI Programming)

Emmanuel Anuoluwa Bamidele
6 min readFeb 23, 2022

While working on some software being used to control power supplies and other major electrical instruments in my lab, I was often frustrated by the return of various unforeseen errors that arises as a result of built-in exceptions or lack of consistency in the type of data returned by the instrument. I started wondering how to go about this and I read scores of resources to amass sufficient knowledge for these kind of challenges. In this article, I will summarise my approach to error handling in python, and provide few examples on its implementation.

The easiest way to handle exception in python is through try statement, followed by the except statement. In the except statement, we can specify a particular error type that we want to handle or leave it to handle all kinds of exceptions. The except block is executed only when the try block returns an error. In the except block, we can write a code to inform the user of the kind of error types or implement a block of code to ignore or fix the error. In the following examples, we show the different examples of using the try, except statement in python:

  1. Writing Exception for a specific error type
def divide(a,b):
c = a/b
return c
try:
divide(5,0)
except ZeroDivisionError:
print("Denominator cannot be zero, check function inputs")
print("Done")

Specifying the type of error in the above block of code can help us to be specific about what the user can do. This approach can be used in cases where we know a wrong data type or wrong input can be entered by the user, expected errors in such cases can be handled like this. The output of the above code looks like this:

output of the code in example 1

2. Writing Exception for all error types

def divide(a,b):
c = a/b
return c
try:
ans = divide(5,0)
print("Answer is:", ans)
except Exception:
print("Can't divide, an error occurred")
print("Done")

In example 2, we replaced the error type in the except statement with only Exception, this will account for all the built-in error types in python and then go ahead to execute the block of statements following the except statement. In this case, we just want to notify the user that an error has occurred. In the next example, we present a case where we can include the particular type of error

output of the code in example 2

3. Writing Exception for all error types, then specifying the error type in the output to the user

def divide(a,b):
c = a/b
return c
try:
Ans = divide(5,0)
except Exception as ex:
format_ = "Error Occured: {0}.\nArguments: {1!r}"
error_message = format_.format(type(ex).__name__, ex.args)
print(error_message)
print("\nDone")

Example 3, shows the possibility of handling all types of errors and making the user know the specific error such that they can know what is going on with their input or the program. First, we define a template (assigned to the variable format_) for the error message to ensure that the most important part of the error message is extracted, then we input the error type obtained into this template using the variable error_message, this was then printed and shown to the user. The output of this program looks like:

output of the code in example 3

4. A case study of when we need to display the error message on the frond end to the user: GUI Programming of a simple calculator

In this example, we build a simple calculator that can take different inputs and perform basic mathematical operations on them. The code, gui and ouput is shown as follow:

a. First we present the code of the GUI containing the program used in computing the calculator and setting up the GUI. Part One of the code contains the necessary libraries and modules that must be imported in order to build the GUI. In part two, we write the code that contains the different functions to enable the user click a button and see it on the screen, evaluate the input, display result and clear the screen. We also included notification so that we can show the user an instruction at the beginning (and after clearing), and when an error occurs. In part three, we wrote a code to build a GUI that constitute the front end of our code.

# PART ONEfrom tkinter import *
from tkinter import scrolledtext
# PART TWOinputs = ""def notification1():
info_box.delete(0.0, END)
info_box.insert(END, "Click to enter inputs")
return
def notification2(message):
info_box.delete(0.0, END)
info_box.insert(END, message)
return
def click(numbers):
global inputs
inputs = inputs + str(numbers)
equation.set(inputs)

def equal_to():

try:
global inputs
answer = str(eval(inputs))
equation.set(answer)

inputs = ""

except Exception as ex:
format_ = "Error Occured: {0}.\nArguments: {1!r}"
error_message = format_.format(type(ex).__name__, ex.args)
notification2(error_message)

def clear_all():
global inputs
inputs = ""
equation.set("")
notification1()
# PART THREE
window = Tk()
window.geometry("250x250")
window.title("© Bamidele 2022")GUI_label = Label(window, font=("Verdana", 12, "bold"), text="Basic Calculator", fg='blue')
GUI_label.place(relx=.25, rely=0.02)
equation = StringVar()
inputs_field = Entry(window, textvariable=equation, fg='red')
inputs_field.place(relx=0.15, rely=0.1)
zero = Button(window, text = "0", fg='black', bg='white',
command=lambda: click(0), height=1, width=2)
zero.place(relx=0.02, rely=0.22)
one = Button(window, text = "1", fg='black', bg='white',
command=lambda: click(1), height=1, width=2)
one.place(relx=0.2, rely=0.22)
two = Button(window, text = "2", fg='black', bg='white',
command=lambda: click(2), height=1, width=2)
two.place(relx=0.4, rely=0.22)
three = Button(window, text = "3", fg='black', bg='white',
command=lambda: click(3), height=1, width=2)
three.place(relx=0.6, rely=0.22)
four = Button(window, text = "4", fg='black', bg='white',
command=lambda: click(4), height=1, width=2)
four.place(relx=0.785, rely=0.22)
five = Button(window, text = "5", fg='black', bg='white',
command=lambda: click(5), height=1, width=2)
five.place(relx=0.02, rely=0.4)
six = Button(window, text = "6", fg='black', bg='white',
command=lambda: click(6), height=1, width=2)
six.place(relx=0.2, rely=0.4)
seven = Button(window, text = "7", fg='black', bg='white',
command=lambda: click(7), height=1, width=2)
seven.place(relx=0.4, rely=0.4)
eight = Button(window, text = "8", fg='black', bg='white',
command=lambda: click(8), height=1, width=2)
eight.place(relx=0.6, rely=0.4)
nine = Button(window, text = "9", fg='black', bg='white',
command=lambda: click(9), height=1, width=2)
nine.place(relx=0.785, rely=0.4)
plus = Button(window, text = "+", fg='black', bg='white',
command=lambda: click("+"), height=1, width=2)
plus.place(relx=0.2, rely=0.56)
minus = Button(window, text = "-", fg='black', bg='white',
command=lambda: click("-"), height=1, width=2)
minus.place(relx=0.4, rely=0.56)
division = Button(window, text = "/", fg='black', bg='white',
command=lambda: click("/"), height=1, width=2)
division.place(relx=0.785, rely=0.56)
multiply = Button(window, text = "x", fg='black', bg='white',
command=lambda: click("*"), height=1, width=2)
multiply.place(relx=0.6, rely=0.56)
Decimal = Button(window, text = ".", fg='black', bg='white',
command=lambda: click("."), height=1, width=2)
Decimal.place(relx=0.02, rely=0.56)
bracket_open = Button(window, text = "(", fg='black', bg='white',
command=lambda: click("("), height=1, width=2)
bracket_open.place(relx=0.02, rely=0.7)
bracket_close = Button(window, text = ")", fg='black', bg='white',
command=lambda: click(")"), height=1, width=2)
bracket_close.place(relx=0.2, rely=0.7)
square = Button(window, text = "^", fg='black', bg='white',
command=lambda: click("**"), height=1, width=2)
square.place(relx=0.4, rely=0.7)
equal_to = Button(window, text = "=", fg='red', bg='white',
command=equal_to, height=1, width=2)
equal_to.place(relx=0.785, rely=0.7)
clear = Button(window, text = "\u239A", fg='red', bg='white',
command=clear_all, height=1, width=2)
clear.place(relx=0.6, rely=0.7)
info_box = scrolledtext.ScrolledText(window, height=2, width=32, wrap=WORD, fg='red')
notification1()
info_box.place(relx=0.02, rely=0.83)
window.mainloop()

b) After running the code, this is what we get (on a Mac Book)

c) In the next figure, we show an example of error message been displayed to the user on the front end using the try, except statement shown in Example 3

An example of error message being displayed to the user on the front end in a formatted style

In summary, the try, except statements offers an easy way to handle exceptions in python programming. This article has shown different examples of such applications, including a case study of displaying a wel formatted message to the user on the front end of a GUI.

--

--

Emmanuel Anuoluwa Bamidele

Bamidele holds a PhD in Materials Science and Engineering from CU Boulder, USA. He is interested in data science, ML, AI & Computational Materials