How to Use Exceptions
In this tutorial, we will see what exceptions are and how to manage them in MicroPython to handle errors in our code.
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.")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.")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.
Let’s see this with a complete example that includes the try, except, else, and finally blocks:
Common Types of Exceptions in MicroPython
MicroPython defines several types of exceptions that we can catch and handle. Some of the most common are:
| Error | Description |
| ZeroDivisionError | Occurs when trying to divide by zero. |
| TypeError | Occurs when an operation is performed with incompatible data types. |
| ValueError | Occurs when an inappropriate value is passed to a function. |
| IndexError | Occurs when trying to access an index out of the bounds of a list or array. |
| NameError | Occurs when trying to use a variable or function that is not defined. |
| OSError | Occurs in operations related to the file system or I/O (e.g., trying to open a file that does not exist). |
