giuspen
giuspen

Reputation: 1401

c++ trivial try-catch causes abort

the simple code below

// g++ centro.cc -o centro

#include <iostream>
using namespace std;

int  main(int argc, char *argv[])
{
    try
    {
        cout << "Going to throw" << endl;
        throw;
    }
    catch(...)
    {
        cout << "An exception occurred" << endl;
    }
    return 0;
}

produces an abort:

Going to throw
terminate called without an active exception
Aborted (core dumped)

I don't understand what's wrong, can anybody point me in the right direction?

Upvotes: 6

Views: 2154

Answers (4)

PlasmaHH
PlasmaHH

Reputation: 16046

This is mandated by the standard (15.1):

8) A throw-expression with no operand rethrows the currently handled exception (15.3). The exception is reactivated with the existing temporary; no new temporary exception object is created. The exception is no longer considered to be caught; therefore, the value of std::uncaught_exception() will again be true.

9) If no exception is presently being handled, executing a throw-expression with no operand calls std:: terminate() (15.5.1).

Upvotes: 3

jcoder
jcoder

Reputation: 30035

throw; on its own rethrows the exception that is currently being processed, but there isn't one in your code.

You need to throw something. Try something like throw std::runtime_error("my message"); instead. You'll need to include #include <stdexcept> for this.

In real code you'll want to create your own exception class to throw most likely

Upvotes: 2

ecatmur
ecatmur

Reputation: 157324

Your line

throw;

is the syntax for re-throwing an exception in a catch block.

You should write:

throw std::exception();

Upvotes: 7

Kos
Kos

Reputation: 72241

Try thowing something. You aren't throwing any exception.

throw; itself is generally used to re-throw the same exception inside a catch block.

Compare the result with throw "something"; or perhaps an instance of std::exception.

Upvotes: 8

Related Questions