Anycorn
Anycorn

Reputation: 51435

C++ catch constructor exception

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++.

Upvotes: 2

Views: 1166

Answers (3)

Potatoswatter
Potatoswatter

Reputation: 137770

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.

Upvotes: 3

Matthew T. Staebler
Matthew T. Staebler

Reputation: 4996

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.

Upvotes: 3

James McNellis
James McNellis

Reputation: 354969

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.

Upvotes: 8

Related Questions