是否可以捕获lambda类型的异常? [英] Is it possible to catch an exception of lambda type?

查看:74
本文介绍了是否可以捕获lambda类型的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然最好只抛出从 std :: exception 类派生的类型的异常,但是C ++可以抛出任何东西。以下所有示例都是有效的C ++:

While it is good practice to throw only exceptions of types derived from std::exception class, C++ makes it possible to throw anything. All below examples are valid C++:

throw "foo";  // throws an instance of const char*
throw 5;      // throws an instance of int

struct {} anon;
throw anon;   // throws an instance of not-named structure

throw []{};   // throws a lambda!

最后一个例子很有趣,因为它可能允许传递某些代码以在捕获站点执行,而不必定义一个单独的类或函数。

The last example is interesting, as it potentially allows passing some code to execute at catch site without having to define a separate class or function.

但是捕获lambda(或闭包)有没有可能? 捕获([] {} e)不起作用。

But is it at all possible to catch a lambda (or a closure)? catch ([]{} e) does not work.

推荐答案

异常处理程序是根据类型进行匹配的,与将异常对象匹配到处理程序的隐式转换相比,在其他上下文中的限制更大。

Exception handlers are matched based on type, and the implicit conversions done to match an exception object to a handler are more limited than in other contexts.

每个lambda表达式都会引入一个闭包类型是周围范围唯一的。因此,您的幼稚尝试无法成功,因为 [] {} 在throw表达式和处理程序中具有完全不同的类型

Each lambda expression introduces a closure type that is unique to the surrounding scope. So your naive attempt cannot work, for []{} has an entirely different type in the throw expression and the handler!

但是你是对的。 C ++允许您抛出任何对象。因此,如果您事先将lambda显式转换为与异常处理程序匹配的类型,它将允许您调用该任意可调用对象。例如:

But you are correct. C++ allows you to throw any object. So if you explicitly convert the lambda before-hand to a type that matches an exception handler, it will allow you to call that arbitrary callable. For instance:

try {
    throw std::function<void()>{ []{} }; // Note the explicit conversion
} catch(std::function<void()> const& f) {
    f();
}

这可能有有趣的用途,但是我要小心,不要扔掉没有得到的东西来自 std :: exception 。更好的选择可能是创建一个从 std :: exception 派生并可以容纳可调用类型的类型。

This may have interesting utility, but I'd caution against throwing things not derived from std::exception. A better option would probably be to create a type that derives from std::exception and can hold a callable.

这篇关于是否可以捕获lambda类型的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆