Paul
Paul

Reputation: 26670

`throw 1` in C++

I a couple of C++ examples I've seen throw 1 in catch block. Tried to find out what it may be, but always found a classical example with exception object or rethrowing an exception without any argument.

Also sometimes I can find in Internet other examples, also without explanations:

throw 1
throw 2
throw -1

Tell me please what it may mean.

Upvotes: 1

Views: 2323

Answers (2)

eerorika
eerorika

Reputation: 238401

throw 1
throw 2
throw -1

Tell me please what it may mean.

throw throws an object. throw 1 throws an object if type int with the value 1. I assume the reader can extrapolate what the other two mean.

This is an exception mechanism. The thrown object can be caught:

try {
    throw 1;
} catch (int e) {
    std::cout << "an integer was thrown and caught. here is the value: " << e;
}

I've seen throw 1 in catch block.

Throwing inside an exception handler is allowed. It has same behaviour as throwing outside a handler.

always found a classical example with exception object or rethrowing an exception without any argument.

This is a case of throwing an exception object.

There is no limitation to the type of objects that can be thrown. The standard library follows the convention of throwing only classes derived from std::exception. Following this convention in user programs is recommended.

Upvotes: 3

Guillaume Racicot
Guillaume Racicot

Reputation: 41780

Tell me please what it may mean.

It means you're throwing a value of a int that has the value 1, 2 or -1.

Of course, without any further detail, it's hard to infer a meaning on this.

A use case would be to report error code from a function:

int returning_error_code() {
    try {
        stuff();
    } catch (int e) {
        return e; // return error code
    }

    return 0; // no error
}

Upvotes: 4

Related Questions