user1873947
user1873947

Reputation: 1811

Catching exception in function thrown from its arguments

void foo(int arg);
int foo2() {throw std::out_of_range("error!"); return 5;}

//Now I do this like that:
try { foo(foo2()); }
catch(std::out_of_range) {}

And what I want to do, is to catch the exception inside the foo function. However I have no idea how can I put try block in the arguments list?

Upvotes: 2

Views: 207

Answers (3)

Patrick Chen
Patrick Chen

Reputation: 81

Most of time, I prefer @iagreen's solution. But in his/her solution, there is a dependence issue:

  • should foo know foo2's signature?

Of course we can get some conclusions in your original call foo(foo2())

  1. the return value of foo2 should be convertible to int
  2. foo does not need to know the amount of foo2's arguments nor their types, even what's the function invoked before foo

So I think a implementation by Variadic Template is more suitable in most cases.

template < typename F, typename... Args >
void foo( F f, Args&&... args ) {
    int ret = f( std::forward<Args>(args)... );
    std::cout << "ret = " << ret << std::endl;
}

Upvotes: 1

iagreen
iagreen

Reputation: 32016

You can't. You either need to pull the call to foo2 out of the call to foo, and handle the exception in the calling routine, as such --

int param;
try { 
   param = foo2(); 
} catch(std::out_of_range) {}
foo(param);

or pass foo2 as a function to foo, and evaluate it inside foo, like this --

void foo(int (*arg_func)()) {
  int arg;
  try { 
    arg = arg_func();
   } catch(std::out_of_range) {
    std::cout << "out of range ";
   }
}

the call then looks like this --

foo(foo2);

Of course, now you always have to pass a function to foo, no literals or expressions.

Upvotes: 2

imulsion
imulsion

Reputation: 9040

you cant, because the exception isnt thrown before foo() was executed.

Upvotes: 2

Related Questions