Exceptions and Exception Handling

An “exception to the rule” is a special case or situation where the rule doesn’t apply.  With this kind of exception, someone usually points it out, and people normally talk together and figure out the best way to handle the exception.

When your micro:bit’s runtime engine encounters an exception to the rules created by your script, it is also called an exception.  But your script can't point it out to you unless you equip it to do that. Statements can be added to scripts telling the micro:bit what to do in response to exceptions.  They are often referred to as exception handling statements, or sometimes just exception handling.  

When an exception is unhandled, it means there are no statements that catch and correct the problem.  In this case, the micro:bit runtime stops executing statements and displays an error message in the LED display with a description and line number.  The most important thing about adding exception handling statements is that they can keep your script running after the exception has occurred, and even fix the problem.

Exception handling code has many variations, but the main ingredients are try and except.

     # Statements that might cause an exception
    # Statements that “handle” the exception so that
    # the micro:bit can keep running its script.

A more complete exception handler might look like this

        # Statements here that might cause an exception.
        # If there was an exception, do something to correct the
        # problem here.
        # If there was not an exception, do these statements.
        # Regardless of whether or not there was an exception,
        # do these statements.

The next example will demonstrate how to test and handle exceptions caused by simple programming errors.  The example after that is especially important because it demonstrates how exceptions caused by user errors (like typing mistakes) can be handled.  With that kind of error handling, you won’t have to restart your micro:bit because it will handle the error by displaying a helpful message and prompting you to try again.