micropython-gestion-de-excepciones

How to Use Exceptions in MicroPython

  • 4 min

In this tutorial, we will see what exceptions are and how to manage them in MicroPython to handle errors in our code.3

An exception is an event that occurs during the execution of a program and interrupts the normal flow of instructions.

These situations can be caused by errors in the code, unexpected conditions in the hardware, or problems with the input data.

In MicroPython, exceptions are objects that represent these errors. When an exception occurs, the program stops unless the exception is caught and handled.

Basic Structure of Exception Handling

In MicroPython, exception handling is done using try and except blocks. The basic structure is as follows:

try:
    # Code that may raise an exception
    result = divide(10, 0)
except ZeroDivisionError:
    # Code that runs if a ZeroDivisionError occurs
    print("Error: Cannot divide by zero.")

Here we place the code that may raise an exception. If an exception occurs within this block, the program flow diverts to the except block.

Here we handle the exception. We can specify the type of exception we want to catch (e.g., ZeroDivisionError) or use a generic except to catch any exception.

This block runs if no exception is raised in the try block.

This block always runs, regardless of whether an exception was raised or not. It is useful for releasing resources or performing cleanup tasks.

Let’s see this with a complete example that includes the try, except, else, and finally blocks:

try:
    result = divide(10, 2)  # This will not raise an exception
except ZeroDivisionError:
    print("Error: Cannot divide by zero.")
else:
    print(f"The result is: {result}")
finally:
    print("End of the try-except block.")

In this example, since no exception is raised, the else and finally blocks execute.

We can also catch multiple types of exceptions in a single try-except block:

try:
    value = int("not a number")  # This will raise a ValueError
except ValueError:
    print("Error: Invalid value.")
except TypeError:
    print("Error: Incorrect data type.")

Common Types of Exceptions in MicroPython

MicroPython defines several types of exceptions that we can catch and handle. Some of the most common are:

ErrorDescription
ZeroDivisionErrorOccurs when trying to divide by zero.
TypeErrorOccurs when an operation is performed with incompatible data types.
ValueErrorOccurs when an inappropriate value is passed to a function.
IndexErrorOccurs when trying to access an index out of the bounds of a list or array.
NameErrorOccurs when trying to use a variable or function that is not defined.
OSErrorOccurs in operations related to the file system or I/O (e.g., trying to open a file that does not exist).

Practical Examples