Exception in try except block not working

Question:

I am trying to create a temperature converter using python’s tkinter module. Inside my converter functions, theres an exception to catch the value error that occurs I enter a value other than an integer or a float. The exception keeps showing up in the terminal but the statement is not being ran. Does anyone know why?

Repl link:
https://replit.com/@jonathanessombe/Project-1#main.py

from tkinter import *

windows = Tk()
windows.geometry('500x200')
windows.title('Temperature converter')


def fahrenheit_convertor():
    degree_entered_1 = round(float(degrees_entry.get()), 2)

    try:
        fahrenheit_output = str(round((9 / 5) * (degree_entered_1) + 32, 2)) + '℉'
    except ValueError:
        display_screen.config(text='Error')
        
    degree_entered_2 = str(degree_entered_1) + '°C'
    display_screen.config(text=degree_entered_2 + ' = ' + fahrenheit_output)


def degrees_convertor():
    farenheit_entered_1 = round(float(farenheit_entry.get()), 2)
    try:
        degree_output = str(round((5 / 9) * (farenheit_entered_1- 32), 2)) + '°C'
        farenheit_entered_2 = str(farenheit_entered_1) + '℉'
        display_screen.config(text=farenheit_entered_2 + ' = ' + degree_output)
    except ValueError:
        display_screen.config(text='Error')

# first row

degrees_label = Label(windows, text='input celsius:')
degrees_label.grid(row=0, column=0, sticky=E)

degrees_entry = Entry(windows)
degrees_entry.grid(row=0, column=1)

fahrenheit_button = Button(windows,
                           text='convert to fahrenheit',
                           command=fahrenheit_convertor)

fahrenheit_button.grid(row=0, column=2)

# 2nd row

farenheit_label = Label(windows, text='input farenheit:')
farenheit_label.grid(row=1, column=0)

farenheit_entry = Entry(windows)
farenheit_entry.grid(row=1, column=1)

degrees_button = Button(windows,
                           text='convert to degrees',
                           command=degrees_convertor)

degrees_button.grid(row=1, column=2, ipadx=6)


# display screen 

display_screen = Label(windows, text='', borderwidth=True)
display_screen.grid(row=2, column=1)

windows.mainloop()

I suspect that the exception is being raised in a different place than you expect.

Look at this part of your function:

def fahrenheit_convertor():
    degree_entered_1 = round(float(degrees_entry.get()), 2)
    try:
        fahrenheit_output = str(round((9 / 5) * (degree_entered_1) + 32, 2)) + '℉'
    except ValueError:
        display_screen.config(text='Error')
    ...

If the user entered "asdf", then the error would occur on the first line of the function, when trying to convert to float. This is outside of the try block.

It is best practice to minimize the amount of code that is in the try block, to make it clearer where the exception actually occurs and to avoid accidentally catching unrelated exceptions.

Also, consider renaming degrees_entry and similar things to be celsius_entry instead.
Another tip is to use formatted string literals (f-strings) to do both rounding and concatenation at once.

def fahrenheit_convertor():
    text_input = degrees_entry.get()
    try:
        degree_entered = float(text_input)
    except ValueError:
        display_screen.config(text='Error')
        return
    fahrenheit_output = (9 / 5) * (degree_entered) + 32
    display_screen.config(text=f'{degree_entered:.2}°C = {fahrenheit_output:.2}°F')

Alternative but equivalent code:

def fahrenheit_convertor():
    text_input = degrees_entry.get()
    try:
        degree_entered = float(text_input)
    except ValueError:
        output = 'Error'
    else:
        fahrenheit_output = (9 / 5) * (degree_entered) + 32
        output = f'{degree_entered:.2}°C = {fahrenheit_output:.2}°F'
    display_screen.config(text=output)
1 Like

why do you have a return statement that returns nothing for the first example you used?

For the second example why do you not have the last line of code in the else statement clause?

why is an else statement needed in the 2nd example?

  1. With functions, it is often useful to end the function’s execution early (to not execute later code in the function). A plain return implicitly returns None, and a function without a return statement also implicitly returns None. (Plain returns are useful for reducing indentation)
  2. The output message will be “Error” if the text entered is not a number. Otherwise, it will be the normal degree conversion output. For both, the output has to be displayed.
  3. The else statement is needed for when there isn’t an error (so that you can convert). Either the except clause or the else clause runs, depending on if there is an error converting to a number.
1 Like