This sort of works for me, and boost can make it even a bit more versatile. However, I doubt you'd be able to make a function for any case where exceptions would be handled:
Code:
#include <iostream>
#include <stdexcept>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
//some functions that can throw
void divide(int a, int b)
{
if (b == 0) {
throw 1;
}
std::cout << a / b << '\n';
}
void print_range(int n)
{
if (n < 0)
throw std::range_error("n is smaller than 0");
for (int i = 0; i != n; ++i) {
std::cout << i << ' ';
}
std::cout << '\n';
}
//dumb error handler
template <class T>
void alert(const T&)
{
std::cout << "An exception happened\n";
}
//slightly better error handler
void print_error(const std::exception& e)
{
std::cout << e.what() << '\n';
}
template <class Except, class Func, class Response>
void try_(Func f, Response r)
{
try {
f();
}
catch (Except& e) {
r(e);
}
}
int main()
{
using namespace boost::lambda;
try_<int>(bind(divide, 10, 2), alert<int>);
try_<int>(bind(divide, 5, 0), alert<int>);
try_<std::exception>(bind(print_range, -10), alert<std::exception>);
try_<std::exception>(bind(print_range, -10), print_error);
try_<std::exception>(bind(print_range, 5), print_error);
}