How to throw an exception in my custom library?

I would like to stop the compilation process if the inputs are invalid. I tried exception classes in the standard C++ library but Arduino does not recognise them. i tried throw "message"; but I got an error exception handling disabled, use -fexceptions to enable. Any ideas?

Thanks.

What do you mean?

Stop the code from uploading to the board. (user side)

Did you mean #error "message" ?

1 Like

Oh thanks.

#if 1 == 1
#error C++ compiler required.
#endif

But why doesn't this work?

bool test() {
    return false;
}

void setup() {
    #if !test()
    #error "message."
    #endif
}

Because the preprocessor can't call a function that hasn't been compiled yet.

1 Like

You can use constexpr functions with static_assert:

constexpr bool test(int i) {
    return i < 42;
}

void setup() {
  static_assert(test(43), "The test failed!");
}

In C++11, you're quite limited in what you can do inside of constexpr functions (basically only return statements), so you'll either have to beg the Arduino developers to enable the newer C++ features by default, or jump through some horrible metaprogramming hoops to get it working in C++11.

1 Like