Blocks#
In Python, a block is a group of statements that belong together, forming the body of a function, loop, class or other structure. A block is defined by an initial line followed by the contents of the block indented four characters.
As an example, a for block sets up a loop:
main.pyThe try-except-finally Block#
There is a try-except-finally structure called a compound statement, consisting of three separate blocks. This is ideal for a main.py file, and is also a very common and useful structure. It is composed of three parts:
- try: this block contains is the code we want to try to execute
- except: this block catches any errors or exceptions that occur and executes the block, handling the exception
- finally: no matter what happens, this block will be executed after the try (and possibly except) blocks are executed
In the below example, there is a try block, followed by an except block, followed by a finally block. A try block must be followed by an except block and/or a finally block (you must have one of them).
main.pyprint('hello world.') # remember to indent the insides of your blocks by 4 characters!
except Exception: # this block is executed if there is an exception (error) print('an error occurred.') finally: # this is always executed, no matter what print('complete.')
If you want to use the exception to print out an error message you need to assign it to a variable (in this case, we've used ex).
main.pyprint('hello world.')
except Exception as ex: # we assign the Exception to the variable 'ex' print('an error occurred: {}'.format(ex)) finally: print('complete.')
Optional Blocks#
As mentioned above, in the try-except-finally compound statement, the except or finally block is optional.
If you don't need to do anything after exiting the try block you can leave off the finally block:
main.pyprint('hello world.')
except Exception: print('an error occurred.')
or, just using finally:
main.pyprint('hello world.')
finally: print('complete.')
Previous: MicroPython Tutorial Exercise 1: main.py
Next: MicroPython Tutorial Exercise 3: functions