I want to log exceptions in a MicroPython program and then restart and report the exception after the restart.
I am having trouble with exceptions from interrupts, see example below:
Code: Select all
import micropython
import pyb
# Raise an arithmetic exception.
try:
x = 1 / 0
except KeyboardInterrupt:
raise
except BaseException as e:
print('Caught arithmetic exception from main: {}.'.format(e))
# Raise an exception from user code.
exception = Exception("User's error") # Statically allocate so that it can be used from an interrupt.
def failure(iterrupt_source):
raise exception
try:
failure(None)
except KeyboardInterrupt:
raise
except BaseException as e:
print('Caught user exception from main: {}.'.format(e))
# Raise an exception after 1/2 a second from an interrupt.
micropython.alloc_emergency_exception_buf(100)
timer = pyb.Timer(4, freq=0.5)
timer.callback(failure)
try:
pyb.delay(1000) # Wait for timer to interrupt and raise exception.
except KeyboardInterrupt:
raise
except BaseException as e:
print('Caught user exception from interrupt: {}.'.format(e))
# Check that you can still use a keyboard interrupt to terminate.
while True:
try:
print('Waiting for Ctrl-C!')
pyb.delay(1000)
except KeyboardInterrupt:
raise
except BaseException as e:
print("Can't imagine how this line is ever reached: {}!".format(e))
Code: Select all
Caught arithmetic exception from main: divide by zero.
Caught user exception from main: User's error.
Waiting for Ctrl-C!
Waiting for Ctrl-C!
uncaught exception in Timer(4) interrupt handler
Traceback (most recent call last):
File "main.py", line 28, in <module>
File "main.py", line 26, in failure
Exception: User's error
Waiting for Ctrl-C!
Traceback (most recent call last):
File "main.py", line 51, in <module>
File "main.py", line 49, in <module>
KeyboardInterrupt:
MicroPython v1.11-167-g331c224e0 on 2019-07-21; PYBv1.1 with STM32F405RG
Any suggestions as to how this might be caught?
Thanks in advance,
-- Howard.