1

I'm currently using caffe but I'm facing a problem. Sometime the library call LOG(FATAL) but I would like to raise an exception and catch it.

I have tried to do my own class defined as below:

#include <stdexcept>
#include <iostream>
#include <sstream>

class FatalException
{
private:
  std::stringstream _ss;
public:
  template<typename T>
  std::ostream& operator<<(const T& obj){
    _ss << obj;
    return _ss;
  }
  ~FatalException(){
    throw std::runtime_error(_ss.str().c_str());
  }
};

The problem is that when I'm doing some testing such as

int main() {
    try {
    FatalException() << "test";
    }
    catch(...) {
    std::cout << "here" << std::endl;
    }
}

the exception is thrown after the try scope

Do you have any hints? Should I overload a stream class and throw an exception when the stream is flushed?

Alexis
  • 2,149
  • 2
  • 25
  • 39
  • I'm not experienced with [tag:caffe] (even if my avatar might imply that), but what's `LOG(FATAL)` actually? Is it a macro called from the library internally? Can you recompile that library and redefine the macro? – πάντα ῥεῖ May 09 '16 at 16:55
  • It's actually from google glog, "Logging a FATAL message terminates the program (after the message is logged)" – Alexis May 09 '16 at 16:56
  • I'm afraid that's the intended behavior there, and you're not supposed to somehow hook or catch it yourself, but you should rather fix the source of the error. But well, as mentioned I'm not an expert about that specific environment. – πάντα ῥεῖ May 09 '16 at 17:00
  • I had to catch exceptions as well. I could not make it work with glog although they have "User-defined Failure Functions". So I had to replace glog with a stream class. In my point of view, it is the best option. Unfortunately I cannot make the code public. – Lefix Aug 11 '16 at 06:33

0 Answers0