views:

126

answers:

3

hi. I do not seem to understand how to catch constructor exception. Here is relevant code:

     struct Thread {
            rysq::cuda::Fock fock_;
            template<class iterator>
            Thread(const rysq::cuda::Centers &centers,
                   const iterator (&blocks)[4])
                : fock_()
            {
                if (!fock_) throw;
           }
      };

      Thread *ct;
      try { ct = new Thread(centers_, blocks); }
      catch(...) { return false; } // catch never happens,

So catch statement do not execute and I get unhandled exception. What did I do wrong? this is straight C++ using g++.

+8  A: 

You have to throw an object, e.g.,

throw std::exception();

throw with no operand is only used inside of a catch block to rethrow the exception being handled by the catch block.

James McNellis
Minor nitpick: it need not be an object. Primitives are okay too.
Billy ONeal
@Billy: in C++, primitives are objects too. An object is simply "a region of storage" (that's somewhere in the very beginning of the language standard).
James McNellis
thank you for your answer as well
aaa
@James McNellis: Good point. D'oh! +1.
Billy ONeal
I'd also argue that throwing primitives, while perfectly legal from the language's point of view, would most likely violate the principle of least surprise and make the catch code even more messy than it usually is.
Timo Geusch
to clearify: `5` isn't an object. Only what is actually thrown and caught is an object (which can be copy of the expression operand).
Johannes Schaub - litb
+3  A: 

You have to throw something in order to catch anything.

Try changing the line

if (!fock_) throw;

to

if (!fock_) throw "";

and observe the difference.

Matthew T. Staebler
thank you for your answer
aaa
+3  A: 

You need to throw something. throw alone means to "re-throw" the current exception. If there is no current exception, unexpected gets called, which will probably abort your program.

It's best to pick a class from <stdexcept> that describes the problem. logic_error or a derivative to indicate programming mistakes, or runtime_error to denote exceptional conditions.

Potatoswatter