micropython-gestion-de-excepciones

How to Use Exceptions in MicroPython

  • 4 min

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

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

These situations can be caused by errors in the code, unexpected hardware conditions, or problems with 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.")
Copied!

Here we place the code that may generate an exception. If an exception occurs inside this block, the program flow is diverted 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 executes if no exception is raised in the try block.

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

Let’s see it with a complete example that includes 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.")
Copied!

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

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.")
Copied!

Common Types of Exceptions in MicroPython

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

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

Practical Examples