As IoT is handling real world events, we have to be extra careful, and take into account ‘exceptions’, when it comes to IoT devices. In practical example this means that we should be prepared to deal with temporary absence of connectivity, or sensor malfunction, without endangering the rest of the system. Think of the example of IIoT (Industrial IoT) where device is designated to measure temperature and pressure in some chemical plant setup. Of course these are crucial for chemical processes, and therefore in case of these values going outside the ‘safe’ limits, should trigger the notification procedure. But now imagine that one of the sensors has failed. Once you try to read it, you get error! What now? Exactly for this kind of situations, we use Try-Except blocks.
Try – Except
try: f = open("demofile.txt") f.write("Lorum Ipsum") f.close() except Exception as e: print("Something went wrong when writing to the file") print("Error is: " + str(e))
In this example we try to open (and write to) the file that does not exist. In a code, without try-except blocks, we would during execution get a message like
File "<stdin>", line 2, in <module> NameError: name 'f' is not defined, as function ‘open()’ failed to execute. Anyhow, this would lead to termination of the programm, and in remote (IoT) devices, we do not want this kind of scenario. That is why we use exception handling.