Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ex.what() changes in nested try-catch

I have a nested try-catch code like below:

void A()
{
    try
    {
        //Code like A = string(NULL) that throws an exception
    }
    catch(std::exception& ex)
    {
        cout<<"in A : " << ex.what();
        throw ex;
    }
}

void B()
{
   try
   {
       A();
   }
   catch(std::exception& ex)
   {
       cout<<"in B : " << ex.what();
   }
}

After running this I got this result:

in A: basic_string::_M_construct null not valid
in B: std::exception

As you can see, ex.what() works OK in function A and tell me the correct description, but in B ex.what() tells me just std::exception. Why does this happen?

Am I throwing something different or wrong in the catch clause of function A? How do I throw a nested exception so that I can get the exact exception description in B?

like image 574
dev-masih Avatar asked Dec 07 '16 12:12

dev-masih


People also ask

How does nested try catch work?

When a try catch block is present in another try block then it is called the nested try catch block. Each time a try block does not have a catch handler for a particular exception, then the catch blocks of parent try block are inspected for that exception, if match is found that that catch block executes.

How do you resolve a nested try catch?

How to Avoid the Nesting? Extracting the nested part as a new method will always work for any arbitrarily nested Try-Catch-Finally block. So this is one trick that you can always use to improve the code.

Can you have nested try catch?

Yes, we can declare a try-catch block within another try-catch block, this is called nested try-catch block.

How do you handle multiple catch blocks for a nested try block explain with an example?

Nested try block is a block in which we can implement one try catch block into another try catch block. The requirement of nested try-catch block arises when an exception occurs in the inner try-catch block is not handled by the inner catch blocks then the outer try-catch blocks are checked for that exception.


2 Answers

Replace throw ex; with throw;.

Doing the latter will re-throw the exception ex, by reference, so obviating the hazards in attempting to make a value copy: see What is object slicing?

(Note that you are allowed to modify ex even if you write throw).

like image 128
Bathsheba Avatar answered Sep 21 '22 06:09

Bathsheba


You are throwing a copy of the exception ex in A. Which causes object slicing that turns the concrete exception into std::exception.

To rethrow the actual exception you caught polymorphically, use the throw; statement.

It's worth keeping in mind what Scott Meyers says in his book. You throw by value, and should catch by reference.

like image 35
StoryTeller - Unslander Monica Avatar answered Sep 22 '22 06:09

StoryTeller - Unslander Monica