Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do the default catch throw statements in C++ pass by value or reference

Tags:

c++

exception

How does the default catch statement catch(...) {} catch an exception, by value or by reference?

Secondly, how does the default throw throw; throw an exception, by value or by reference?

like image 560
user236215 Avatar asked Mar 05 '12 05:03

user236215


2 Answers

The catch-all catch (...) doesn't give you access to the exception object at all, so the question is moot. [Corrected:] Rethrowing with throw; throws the original object. If the handler catches by value, then changes to the local copy do not affect the original, rethrown object.[/] See 15.3 (esp. clause 17) for details.

Check out some of the related questions on the right, like this one or this one and this one and this one.

like image 94
Kerrek SB Avatar answered Oct 02 '22 22:10

Kerrek SB


You always catch what you have thrown. Let's say you have an exception class

class MyException {
public:
    int m_data;
    MyException(int data) 
    { 
        printf("MyException::MyException() ctor\n"); 
        m_data = data;   
    }

    MyException(const MyException & other)    { 
        printf("MyException::MyException() copy ctor\n");
    }

    ~MyException()
    {
        printf("MyException::~MyException() dtor\n");
    }
};

1) If you have thrown a pointer, you'll get the pointer:

Example 1:

void f()
{
    throw new MyException()
}

void main()
{
    try{
        f();
    }    
    catch(MyException * ex) // You WILL catch the pointer
    {
        delete ex; // You should delete the exception object
    }
    catch(MyException & ex) // You WILL NOT catch the pointer
    {
    }
}

Example 2:

void main()
{
     try{
         f();
     }
     catch(...) // You WILL catch the pointer, but will be unable to access it
     {
         throw; // You are rethrowing the pointer
     } 
 }

2) If you have thrown an object, you'll catch a reference to it:

Example 1:

void f()
{
    printf("f BEGIN\n");
    throw MyException(1); // MyException ctor is called
    printf("f END\n");
}

void main()
{
    printf("main BEGIN\n");

    try
    {
        f();
    }
    catch(MyException & ex)  // You WILL catch a reference to created object
    {
       printf("catch MyException: %d\n", ex.m_data);
    } // MyException dtor is called here!!

    printf("main END\n");
}

The following output is produced:

main BEGIN
f BEGIN
MyException::MyException() ctor
catch MyException: 1
MyException::~MyException() dtor
main END

Example 2:

void main()
{
     try
     {
         f();
     }
     catch(...)  // You WILL catch a reference to created object, 
                 //but will be unable to access it
     {
         throw; // You throw the reference
     }
 }
like image 45
blackbada_cpp Avatar answered Oct 02 '22 22:10

blackbada_cpp