Exceptions not working on the Seeeduino XIAO even when enabled

I’m trying to enable exceptions on the Seeeduino XIAO. I added the following lines to the platformio.ini file:

build_flags = -fexceptions
build_unflags = -fno-exceptions

I test with this simple code:

#include <Arduino.h>
#include <stdexcept>

void setup() {
	Serial.println("starting exception handling test");
	try {
		throw std::runtime_error("");
	} catch (const std::runtime_error&) {
		Serial.println("caught exception");
	}
	Serial.println("finished exception handling test");
}

void loop() {}

It compiles fine, but it only prints

starting exception handling test

In other words, it doesn’t executes the catch block or everything after it. It just hangs whenever an exception is thrown.

How to enable exceptions on this board?

Same problem here !

Did you find a solution ?

Most firmwares link with --specs=nano.specs, i.e. “newlib-nano”. This stripped down C library version does not support exceptions, it justs std::abort()s when it encounters one. Please check in the project task Advanced → Verbose Build wether that flag is included in the final linker command. If yes, you can attempt to remove it by manipulating env["LINKFLAGS"]with some advanced scripting.

Doing so is however an automatic death sentence in regards to the used FLASH size. Linking in the full C library will provide exceptions at the cost of significantly blowing up the firmware size. In most cases, this is not worth it. Hence why virtually all Arduino cores for size-constrained devices build with -fno-exceptions and newlib-nano.

Only a few cores for devices with a significantly large flash do this, e.g., Espressif 8266 devices, in this case implemented by linking a differently built C++ library (special for their XTensa toolchain).

1 Like

Thank you ! That was a very detailed and fast answer !

All make sens now