捕捉lambda异常(Catching lambda exception)

我如何捕获作为例外抛出的lambda? 我尝试了以下方法:

#include <functional> int main() { try { throw [](){}; } catch (std::function<void()> & fn) { fn(); } }

但输出是

在抛出'main :: {lambda()#1}的实例后终止调用

是否有可能捕获抛出的lambda异常?

How can I catch a lambda thrown as an exception? I tried the following:

#include <functional> int main() { try { throw [](){}; } catch (std::function<void()> & fn) { fn(); } }

However the output is

terminate called after throwing an instance of 'main::{lambda()#1}'

Is it possible to catch thrown lambda exception?

最满意答案

你可以显式抛出一个std::function :

int main() { try { throw std::function<void()>([](){std::cout << "Hello there!";}); } catch (std::function<void()> & fn) { fn(); } }

You can throw an std::function explicitly:

int main() { try { throw std::function<void()>([](){std::cout << "Hello there!";}); } catch (std::function<void()> & fn) { fn(); } }捕捉lambda异常(Catching lambda exception)

我如何捕获作为例外抛出的lambda? 我尝试了以下方法:

#include <functional> int main() { try { throw [](){}; } catch (std::function<void()> & fn) { fn(); } }

但输出是

在抛出'main :: {lambda()#1}的实例后终止调用

是否有可能捕获抛出的lambda异常?

How can I catch a lambda thrown as an exception? I tried the following:

#include <functional> int main() { try { throw [](){}; } catch (std::function<void()> & fn) { fn(); } }

However the output is

terminate called after throwing an instance of 'main::{lambda()#1}'

Is it possible to catch thrown lambda exception?

最满意答案

你可以显式抛出一个std::function :

int main() { try { throw std::function<void()>([](){std::cout << "Hello there!";}); } catch (std::function<void()> & fn) { fn(); } }

You can throw an std::function explicitly:

int main() { try { throw std::function<void()>([](){std::cout << "Hello there!";}); } catch (std::function<void()> & fn) { fn(); } }