Is an exception specification needed if the method throws and catchesits own exception?

E

elcapitan666

Is an exception specification need if the method itself throws and
catches its own exception? ie

void foo( ) throw( runtime_error )
{
fstream infile;

try
{
infile.open( "myfile.txt" );

if( !infile )
throw runtime_error( "Error opening file" );
}

catch( runtime_error & err )
{ cout << err.what( ) << endl; }
}
 
A

Alf P. Steinbach

* (e-mail address removed):
Is an exception specification need if the method itself throws and
catches its own exception? ie

void foo( ) throw( runtime_error )
{
fstream infile;

try
{
infile.open( "myfile.txt" );

if( !infile )
throw runtime_error( "Error opening file" );
}

catch( runtime_error & err )
{ cout << err.what( ) << endl; }
}

An exception specification is never neeeded, and it specifies not what
goes on inside the function but whether and what the function can throw
to its caller.

The only exception specification that will pass a decent code review, is
the empty exception specification, which documents that you don't intend
the function to ever throw any exception.

Personally I value clarity over micro-efficiency so from my point of
view an empty exception specification is fine, and perhaps "throw(
std::exception )" to assure the reader that if any exception is thrown
it will be one compatible with std::exception, can be acceptable
(although what it says is implicit in modern code), but any other
exception specification indicates low quality code (because the
programmer hasn't understood the language). It's a mystery how the
general exception specifications came to be added to the language.
Presumably it was a committee "political" compromise.

Cheers, & hth.,

- Alf
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,072
Latest member
trafficcone

Latest Threads

Top