Why should I use catch by reference when calling exception pointers

When catching an exception by reference, the only benefit I get is to avoid copying the created exception object? Basically the difference between

try
{
    CString a_csSQL = _T("SELECT * FROM Library");
    CDatabase aDB;
    aDB.OpenEx(g_csConnectionStringWdDSN,CDatabase::noOdbcDialog));
    aDB.ExecuteSQL(a_csSQL);
}
catch(CDBException *& ex)
{
    ex->Delete();
}

      

and

try
{
    CString a_csSQL = _T("SELECT * FROM Library");
    CDatabase aDB;
    aDB.OpenEx(g_csConnectionStringWdDSN,CDatabase::noOdbcDialog))
    aDB.ExecuteSQL(a_csSQL);
}
catch(CDBException * ex)
{
    ex->Delete();
}

      

+3


source to share


2 answers


The difference between the two codes you quoted is that the first catches a pointer to an exception by reference, and the second catches a pointer to an exception by value. The exception is not copied anyway, since you are dealing with pointers.

In general, exceptions should be thrown by value and caught by reference. The C ++ Standard Library is designed with this expectation in mind. However, older libraries (like MFC) throw exceptions by pointer like you do here and must be caught by pointer.



There is no effective difference between catching a pointer by value and a reference, except if you catch by a reference that gives you the (completely useless) option to drop the exception, throwing a new exception with that same pointer and reverse engineering the same exception pointer.

+7


source


If the exception is thrown by a pointer, you can avoid using a reference.



Links are really needed if the exception is thrown by value.

0


source







All Articles