Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of exception object in C++

What is the scope of the exception object in C++? does it go out of scope as soon as catch handler is executed? Also, if I create an unnamed exception object and throw it, then while catching that exception does it matter if I catch it by const reference or a non-const reference?

like image 557
Naveen Avatar asked Oct 31 '09 11:10

Naveen


People also ask

What are exceptions in C?

C # in Telugu C++ exception handling is built upon three keywords: try, catch, and throw. throw − A program throws an exception when a problem shows up. This is done using a throw keyword. catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem.

Where does the exceptions are used?

Explanation: Exceptions are used when postconditions of a function can be satisfied.

Can we handle exceptions in C?

C doesn't support exception handling.

What are the advantages of exceptions in C++?

The advantage of exceptions are two fold: They can't be ignored. You must deal with them at some level, or they will terminate your program. With error code, you must explicitly check for them, or they are lost.


1 Answers

When a throw expression is evaluated, an exception object is initialized from the value of the expression. The exception object which is thrown gets its type from the static type of the throw expression ignoring any const and volatile qualifiers. For class types this means that copy-initialization is performed.

The exception object's scope is outside of the scope of the block where the throw occurs. Think of it as living in a special exception area off to one side of the normal call stack where local objects live.

Inside a catch block, the name initialized with the caught exception object is initialized with this exception object and not the argument to throw, even if this was an lvalue.

If you catch via non-const reference, then you can mutate the exception object, but not what it was initialized from. You can alter the behaviour of the program if you re-throw the exception in ways that you couldn't if you caught by value or const reference (const_casts aside).

The exception object is destroyed when the last catch block that does not exit via a re-throw (i.e. a parameterless throw expression evaluation) completes.

like image 125
CB Bailey Avatar answered Sep 25 '22 20:09

CB Bailey