Page 1 of 1

What type of exception does MicroPython raise when the stop button is pressed in Thonny?

Posted: Tue Mar 29, 2022 3:46 am
by kyuchumimo
If I write a code that for example looks something like this:

Code: Select all

try:
    while True:
        time.sleep(1)
        pass
except:
    #Code that will be executed if the stop button is pressed in Thonny
    with open('data.txt', 'w') as f:
        f.write("Exception raised")
The code inside except is executed if Thonny's stop button is pressed, but as you may know, placing an except without defining which exception to handle is not a good practice.
So I need to know exactly the exception to be able to reset the state of the pins and other external elements like displays, otherwise if a different exception occurs, I will not be able to know its cause.
I should also clarify that in Python, the code inside except is not executed if the stop button is pressed, it only happens in MicroPython.

Re: What type of exception does MicroPython raise when the stop button is pressed in Thonny?

Posted: Tue Mar 29, 2022 5:49 am
by kyuchumimo
I discovered by trial and error that when pressing stop in Thonny, the KeyboardInterrupt exception is raised.
Now, I need to figure out how to execute code inside the except block for any exception and print that exception.

Related topic: viewtopic.php?t=11901

Re: What type of exception does MicroPython raise when the stop button is pressed in Thonny?

Posted: Tue Apr 05, 2022 5:31 pm
by dhylands
You can use sys.print_exception(), which is documented here.

An example of it being used can also be found here: https://github.com/dhylands/upy-example ... int_exc.py

Re: What type of exception does MicroPython raise when the stop button is pressed in Thonny?

Posted: Thu Apr 14, 2022 7:42 am
by Nicolett
Thank you Dave. You saved me a lot of time