Re: Unhandled Exception Question
On 10/4/2010 7:52 PM, Immortal Nephi wrote:
On Oct 4, 5:30 am, Michael Doubez<michael.dou...@free.fr> wrote:
On 4 oct, 05:21, Immortal Nephi<Immortal_Ne...@hotmail.com> wrote:
I looked at vector?s header. I only see that there is only throw in
some functions, but they don?t have try / catch block.
If try / catch block is not written, then throw will be executed to
the operating system directly to trigger unhandled exception.
Correct?
Not exactly.
If no handler is found, std::terminate() is called.
It the exception if thrown from a object's constructor/destructor
whith static storage duration, the exceptions are not caught.
Let me understand clearly.
void foo( int index ) {
if ( index< 0 || index> 15 )
throw;
}
This function does not have try / catch block. If throw is executed,
then terminate() function is called. Correct?
Maybe you suggest to put terminate() function inside foo() function
to replace throw. You can write your own terminate() function and
uses set_terminate().
No. As written, it calls terminate(), but only if foo() is not called
by an exception handler.
What you are thinking of is:
#include <stdexcept>
void foo(int index)
{
if (index < 0 || index > 15)
throw std::runtime_error("bad index");
}
In this case, what happens if someone in the call stack that eventually
invoked foo() has an exception handler for std::runtime_exception, then
that handler will be invoked. For example, in the code below, even
though there's no handler in foo(), terminate() is not called, because
the call stack has a handler for runtime_error.
// definition of foo as above.
#include <iostream>
#include <ostream>
void g()
{
foo(27);
}
void f()
{
g();
}
void h()
{
try
{
f();
}
catch(std::runtime_error& e)
{
std::cout << "Runtime error "
<< e.what()
<< std::endl;
}
}
int main()
{
h();
}