Error handling on temperature sensor I built an allsky camera with a temperature sensor and a heater. The heater is supposed to turn when the sensor (measure_temp()) return a temperature below 8, which is checked every 15 minutes. However, about every 4th measurement fails and so I included an error handler that returns 7, so that the heater turns on if the sensor returns an error, but it seems like a bad solution. Is there a better way to handle the error like run the function until no error occurs?
import RPi.GPIO as GPIO
import time
import datetime
import time
import board
import adafruit_dht

def measure_temp():
    dhtDevice = adafruit_dht.DHT22(board.D18)

    try:
        temperature = dhtDevice.temperature
        error_test = &quot;&quot;
    except RuntimeError as error:
        temperature = 7
    except:
        temperature = 7        
    return temperature


if __name__ == '__main__':

    while True:
        if  measure_temp() &lt; 8:
            GPIO.setmode(GPIO.BCM)
            RELAIS_1_GPIO = 17
            GPIO.setup(RELAIS_1_GPIO, GPIO.OUT)
            GPIO.output(RELAIS_1_GPIO, GPIO.HIGH)
            print('{:%d.%m.%Y %H:%M:%S}'.format(datetime.datetime.now()))
            print('Heating on')
            print()
            time.sleep(900)
            GPIO.cleanup()
        else:
            GPIO.setmode(GPIO.BCM)
            RELAIS_1_GPIO = 17
            GPIO.setup(RELAIS_1_GPIO, GPIO.OUT)
            GPIO.output(RELAIS_1_GPIO, GPIO.LOW)
            print('{:%d.%m.%Y %H:%M:%S}'.format(datetime.datetime.now()))
            print('Heating off')
            time.sleep(900)
            GPIO.cleanup()
Every 4th measurement fails is a pretty high error rate. The preferred course of action would be to root cause the error and fix it. Meanwhile, since the error seems to be transient, you may want to read the sensor again, and again, until it reads cleanly. Another strategy is to read more often, and maintain the running average (discarding the failures).
For a proper review, DRY. The GPIO setup shall be lifted out of the if/else:
while True:
    GPIO.setmode(GPIO.BCM)
    RELAIS_1_GPIO = 17
    GPIO.setup(RELAIS_1_GPIO, GPIO.OUT)
    if  measure_temp() &lt; 8:
        GPIO.output(RELAIS_1_GPIO, GPIO.HIGH)
        print('{:%d.%m.%Y %H:%M:%S}'.format(datetime.datetime.now()))
        print('Heating on')
        print()
    else:
        GPIO.output(RELAIS_1_GPIO, GPIO.LOW)
        print('{:%d.%m.%Y %H:%M:%S}'.format(datetime.datetime.now()))
        print('Heating off')
    time.sleep(900)
    GPIO.cleanup()

I also recommend to factor the printing out to the function, e.g.
def log_heating_status(status):
    print('{:%d.%m.%Y %H:%M:%S}'.format(datetime.datetime.now()))
    print('Heating {%s}'.format(status))

to be called as log_heating_status('on') and log_heating_status('off').
It is also very unclear why do you setup/cleanup GPIO on every iteration. I'd expect it to be done once, outside the loop.