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

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
kyuchumimo
Posts: 3
Joined: Sun Mar 20, 2022 1:14 am

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

Post by kyuchumimo » Tue Mar 29, 2022 3:46 am

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.

kyuchumimo
Posts: 3
Joined: Sun Mar 20, 2022 1:14 am

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

Post by kyuchumimo » Tue Mar 29, 2022 5:49 am

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

User avatar
dhylands
Posts: 3821
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

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

Post by dhylands » Tue Apr 05, 2022 5:31 pm

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

Nicolett
Posts: 7
Joined: Mon Apr 11, 2022 1:16 pm

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

Post by Nicolett » Thu Apr 14, 2022 7:42 am

Thank you Dave. You saved me a lot of time

Post Reply