C++ Logo

std-proposals

Advanced search

[std-proposals] throw = runtime_error;

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Sun, 13 Aug 2023 15:24:39 +0100
What if we could set the type of what's thrown within a try block, as
follows:

try
{
    throw = std::runtime_error;

    if ( something ) throw "bad happened";

    if ( something ) throw "worse happened;

    throw = std::logic_error;

    if ( something ) throw "even worse happened";
}

In the above snippet, the first two 'throw' statements throw an object of
type 'runtime_error', and the third throws an object of type 'logic_error'.

You could consider this feature to merely be a form of shorthand, but it
could also be a versatile way of changing one line of code to affect much
larger blocks of code.

Of course the compiler would always need to know, at compile time, the type
of what's thrown, and so you couldn't do the following:

try
{
    throw = std::runtime_error;

    if ( something ) throw "bad happened";

    if ( something ) throw "worse happened;

    if ( something ) throw = std::logic_error;
                        else throw = std::domain_error;

    if ( something ) throw "even worse happened";
}

If you have nested try blocks inside a function, I think the "throw = type"
should propagate into the nested blocks, however it should not propagate
into a nested function call.

Received on 2023-08-13 14:24:42