Catching lambda exceptions

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

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

However conclusion

ending a call after calling the instance 'Home :: {lambda () # 1}'

Is it possible to catch the thrown lambda exception?

+4
source share
4 answers

You can explicitly specify std::function:

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

Two reasons this exception handler will fail:

  • You catch your exception lvaluewith an object reference std::function<void()>, but an abandoned object of this type is not and is not the base class of the abandoned object.

  • Even if you change the parameter to a value, std::function<void()>it will not be created from lambda in exception handling. Cm.


"". . by SingerOfTheFall skypjack

+1

, std::function. , - , std::function.

, std::function .
( , ):

#include <functional>
#include<utility>
#include<type_traits>
#include<iostream>

struct Base {
    virtual void operator()() = 0;
};

template<typename F>
struct Lambda: F, Base {
    Lambda(F &&f): F{std::forward<F>(f)} {}
    void operator()() override { F::operator()(); }
};

template<typename F>
auto create(F &&f) {
    return Lambda<std::decay_t<F>>{std::forward<F>(f)};
}

int main() {
    try {
        throw create([](){ std::cout << "doh" << std::endl; });
    } catch (Base &fn) {
        fn();
    }
}
+1

The main requirement when circumventing an exception is to have a certain type for the object you are catching. Lambda do not have a specific, clean type that you can use. The pure way to do this is to wrap your lambda with std::function, and then know exactly what you are catching.

0
source

Source: https://habr.com/ru/post/1670265/


All Articles