catching assertion error

E

Eric

is it possible to catch an assertion error? that is, could the following
block of code be made to run?

assert (false);
catch (...) {}
 
M

mlimber

Eric said:
is it possible to catch an assertion error? that is, could the following
block of code be made to run?

assert (false);
catch (...) {}

No. Asserts are different from exceptions, and if you want to catch,
you must throw.

Cheers! --M
 
?

=?ISO-8859-15?Q?Juli=E1n?= Albo

Eric said:
is it possible to catch an assertion error? that is, could the following
block of code be made to run?
assert (false);
catch (...) {}

The standard assert just prints some information and calls abort. Of course
you can write your own assert macro and not include the standard header,
but is clearer to use another name, such as ASSERT, MY_PROJECT_ASSERT... or
better yet, don't use in the name nothing similar to assert if you want to
use it as an exception and not as an assertion. For example, something like
LOGIC_CHECK that throws std::logic_error if failed looks reasonable to me.
 
S

Salt_Peter

Eric said:
is it possible to catch an assertion error? that is, could the following
block of code be made to run?

assert (false);
catch (...) {}

No, if you want to catch, someone has to throw the ball (or whatever).

#include <iostream>
#include <stdexcept>

int main()
{
try
{
throw std::logic_error( "testing logic_error" );
}
catch ( const std::exception& r_e )
{
std::cerr << "error: " << r_e.what() << std::endl;
}
}

/*
error: testing logic_error
*/

Can you see why its a bad idea to catch(...) as opposed to a specific
catch?
 
M

mlimber

VJ said:
Why is it a bad idea to catch all?
It has some good uses

He's not suggesting it's *always* a bad idea to catch all exceptions,
but in the example he gave, it is better to catch a specific exception
(or rather, a specific class of exceptions).

Cheers! --M
 
S

Salt_Peter

VJ said:
Why is it a bad idea to catch all?
It has some good uses

Consider the list of possible standard exceptions that might be thrown:
ios_base::failure
bad_alloc
bad_cast
logic_error
runtime_error
bad_exception

It would be a shame to catch any of these in a carch-all for obvious
reasons.

#include <iostream>
#include <stdexcept>

int main()
{
try {
// may throw
}
catch ( const std::logic_error & e ) {
std::cerr << "a logic_error was caught: ";
std::cerr << e.what() << std::endl;
}
catch ( const std::exception & e ) {
std::cerr << "a specific error was caught: ";
std::cerr << e.what() << std::endl;
}
catch ( ... ) {
std::cerr << "an undetermined error occurred\n";
}
}
 

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

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,527
Members
44,998
Latest member
MarissaEub

Latest Threads

Top