Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function try block. An interesting example

Consider the following C++ program

struct str
{
       int mem;
       str()
       try
          :mem(0)
       {
               throw 0;
       }
       catch(...)
       {
       }
};

int main()
{
       str inst;
}

The catch block works, i.e. the control reaches it, and then the program crashes. I can't understand what's wrong with it.

like image 872
Armen Tsirunyan Avatar asked Oct 08 '10 08:10

Armen Tsirunyan


People also ask

What is the function of try block?

A function try block on main() does not catch exceptions thrown in destructors of objects with static storage duration, or constructors of namespace scope objects. The following example throws an exception from a destructor of a static object.

What type of statements are placed in a try block?

A try block must enclose the statements that can throw exceptions. A try block begins with the try keyword followed by a sequence of program statements enclosed in braces. Following the try block is a list of handlers called catch clauses.

What should be put in a try block 1 statements?

What should be put in a try block? Explanation: The statements which may cause problems are put in try block. Also, the statements which should not be executed after a problem accursed, are put in try block. Note that once an exception is caught, the control goes to the next line after the catch block.

What happens if try catch block is not used in C++?

The technical term for this is: C++ will throw an exception (error).


1 Answers

Once the control reaches the end of the catch block of function-try-block of a constructor, the exception is automatically rethrown. As you don't catch it further in main(), terminate() is called. Here is an interesting reading: http://www.drdobbs.com/184401316

like image 185
usta Avatar answered Oct 12 '22 17:10

usta