Page 1 of 1
A way to catch any exception?
Posted: Fri Jun 23, 2017 5:56 am
by eradicatore
I notice that when my python has an error, I get the REPL prompt on serial. Is there a way to do something in code when this exception happens, like blink an LED for example? Where is this REPL prompt coming from? Is it embedded in the micropython binary to go to that for unhandled exceptions?
Justin
Re: A way to catch any exception?
Posted: Fri Jun 23, 2017 8:24 am
by pythoncoder
This is a query about the Python language rather than anything specific to MicroPython. There are plenty of books and online tutorials which can help you and I suggest getting familiar with the language on a PC. In essence if your program stops for any reason (e.g. running to completion or throwing an exception), you get back to the REPL. To catch exceptions you use code like this:
Code: Select all
try:
# something which might raise an OSError
except OSError:
# Flash an LED
It is possible to catch and ignore any exception as below, but it is bad practice because syntax errors will be ignored so you'll never find your bugs.
Code: Select all
try:
# lots of code
except:
pass # very bad idea
Re: A way to catch any exception?
Posted: Fri Jun 23, 2017 11:21 am
by eradicatore
Ok, thanks! Yea, I was mainly asking about your comment "if it stops for any reason". I should have mentioned I'm already familiar with the try/except format, but was looking for a "global" version to do something if my board dies this way and I didn't have the try/except around the culprit
Re: A way to catch any exception?
Posted: Tue Jun 27, 2017 6:27 am
by Damien
When a script finishes (either it runs to the end or has an uncaught exception) then the MicroPython runtime will go to the REPL.
If you want to catch any exception and handle that (eg reset the device) then do as suggested above, run your outer-most code in a try/except block, and do the error handling in the except.
Re: A way to catch any exception?
Posted: Wed Feb 06, 2019 2:15 pm
by radders
I've got some code:
Code: Select all
except OSError as exc:
if exc.args[0] == uerrno.EWOULDBLOCK:
print ('EWOULDBLOCK')
time.sleep(1) # short delay, no tight loops
which came from a sample on a forum, but I get errors at the
uerrno line.
What is the correct implementation for this port of MicroPython, please?
Detecting when a nonblocking socket would block
Posted: Wed Feb 06, 2019 5:38 pm
by pythoncoder
I think the
EWOULDBLOCK error dates back to an older version of Python. The correct line (for Python 3.4 and hence for MicroPython) is:
Re: A way to catch any exception?
Posted: Mon Mar 11, 2019 1:53 pm
by radders
Peter,
I'm getting:
Code: Select all
NameError: name 'errno' isn't defined
Dave
Re: A way to catch any exception?
Posted: Mon Mar 11, 2019 4:09 pm
by kevinkk525
You need to import errno.
Re: A way to catch any exception?
Posted: Wed Mar 20, 2019 2:02 pm
by radders
TY. Simple when you know how