473,219 Members | 1,659 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,219 software developers and data experts.

try-catch blocks & memory leaks

Below are three try-catch blocks. My question is, how can all three work,
and how come there is no memory leak (or is there)? As I understand it, an
exception object is being created and "thrown" back to the calling function.
If you treat this object as a reference or copy it, how does it get cleaned
up?

/* code segment 1 */
try {
m_pCommand->Execute(NULL, NULL, adCmdText | adExecuteNoRecords);
}
catch(_com_error *e) { // pointer
DumpComError(e);
delete e;
return NULL;
}

/* code segment 2 */
try {
m_pCommand->Execute(NULL, NULL, adCmdText | adExecuteNoRecords);
}
catch(_com_error &e) { // reference
DumpComError(e);
// can't delete e
return NULL;
}

/* code segment 3 */
try {
m_pCommand->Execute(NULL, NULL, adCmdText | adExecuteNoRecords);
}
catch(_com_error e) { // copy of original error
DumpComError(e);
// can't delete e
return NULL;
}

/* done */

TIA,
C. Martin

Jul 22 '05 #1
4 9589
* "Chris Martin" <no****@please11111.net> schriebt:
Below are three try-catch blocks. My question is, how can all three work,
The blocks you show seems to have different assumptions about what 'Execute'
throws.
and how come there is no memory leak (or is there)?
Your first example has a possible memory leak.
As I understand it, an
exception object is being created and "thrown" back to the calling function.
If you treat this object as a reference or copy it, how does it get cleaned
up?
Each copy of the object is cleaned up via a call to its destructor.

/* code segment 1 */
try {
m_pCommand->Execute(NULL, NULL, adCmdText | adExecuteNoRecords);
}
catch(_com_error *e) { // pointer
This catches a 'com_error*'. It does not catch a 'com_error'.
DumpComError(e);
Here is a possible memory leak: if 'DumpComError' throws then 'delete'
will not be called.
delete e;
return NULL;
}

/* code segment 2 */
try {
m_pCommand->Execute(NULL, NULL, adCmdText | adExecuteNoRecords);
}
catch(_com_error &e) { // reference
This catches a 'com_error'. It does not catch a 'com_error*'. By the way,
as a matter of good coding style you should never catch by reference to
non-const, as is done here, but only by reference to const.
DumpComError(e);
// can't delete e
return NULL;
}

/* code segment 3 */
try {
m_pCommand->Execute(NULL, NULL, adCmdText | adExecuteNoRecords);
}
catch(_com_error e) { // copy of original error
This catches a 'com_error'. It does not catch a 'com_error*'. To avoid
excessive copying overhead catch by reference to const instead.

DumpComError(e);
// can't delete e
return NULL;
}


Jul 22 '05 #2
The blocks you show seems to have different assumptions about what 'Execute' throws.
I can't seem to find any documentation on -what- Execute throws. I believe
all three catches worked correctly though.
Each copy of the object is cleaned up via a call to its destructor.


When is the destructor called? For a reference I can't delete it in order
for the destructor to be called. Wouldn't it have to be on the heap? Same
with the copied object.
/* code segment 1 */
try {
m_pCommand->Execute(NULL, NULL, adCmdText | adExecuteNoRecords);
}
catch(_com_error *e) { // pointer


This catches a 'com_error*'. It does not catch a 'com_error'.


I don't understand your point.
DumpComError(e);


Here is a possible memory leak: if 'DumpComError' throws then 'delete'
will not be called.


But if it doesn't, when will delete be called?

I obvoiusly have a flawed understanding of how exception handling really
works.

Thanks for the reply,
C. Martin
Jul 22 '05 #3
Chris Martin wrote:
The blocks you show seems to have different assumptions about what
'Execute' throws.
I can't seem to find any documentation on -what- Execute throws.


Then it's a case of extremely bad documentation.
I believe all three catches worked correctly though.
That's very unlikely. The function cannot throw two types at the same
time, and a _com_error and a pointer to it are two separate and
unrelated types.
Each copy of the object is cleaned up via a call to its destructor.


When is the destructor called? For a reference I can't delete it in
order
for the destructor to be called. Wouldn't it have to be on the heap?
Same with the copied object.
> /* code segment 1 */
> try {
> m_pCommand->Execute(NULL, NULL, adCmdText | adExecuteNoRecords);
> }
> catch(_com_error *e) { // pointer


This catches a 'com_error*'. It does not catch a 'com_error'.


I don't understand your point.


_com_error* and _com_error are different types. The above will only
catch if a pointer to _com_error was thrown, not if a _com_eror was
thrown directly.
> DumpComError(e);


Here is a possible memory leak: if 'DumpComError' throws then
'delete' will not be called.


But if it doesn't, when will delete be called?


What do you mean? If DumpComError doesn't throw, then delete will be
called afterwards. That's what you wrote in your code.
I obvoiusly have a flawed understanding of how exception handling
really works.


Maybe. But I have no idea what your exact understanding of it is.

Jul 22 '05 #4
"Chris Martin" <no****@please11111.net> wrote in message news:<pPA%b.69050$4o.90319@attbi_s52>...
The blocks you show seems to have different assumptions about what 'Execute'
throws.


I can't seem to find any documentation on -what- Execute throws. I believe
all three catches worked correctly though.


That depends on your definition of "correctly".
Each copy of the object is cleaned up via a call to its destructor.
When is the destructor called? For a reference I can't delete it in order
for the destructor to be called. Wouldn't it have to be on the heap? Same
with the copied object.


This is done by the errorhandling mechanism: it is responsible for
cleaning up your exception-objects.
/* code segment 1 */
try {
m_pCommand->Execute(NULL, NULL, adCmdText | adExecuteNoRecords);
}
catch(_com_error *e) { // pointer


This catches a 'com_error*'. It does not catch a 'com_error'.


I don't understand your point.

[snip]

try running this snippet (not tested)

try
{
int throwval(0);
throw throwval; // throw an integer
}
catch (int i)
{
std::cout << "caught int: " << i << '\n';
}
catch (int *pi)
{
std::cout << "caught pointer to int: " << pi << '\n';
}
catch (...)
{
std::cout << "caught something else" << '\n';
}
try
{
int* throwval(0);
throw throwval; // throw a pointer to an integer
}
catch (int i)
{
std::cout << "caught int: " << i << '\n';
}
catch (int *pi)
{
std::cout << "caught pointer to int: " << pi << '\n';
}
catch (...)
{
std::cout << "caught something else" << '\n';
}
Jul 22 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

39
by: Erlend Fuglum | last post by:
Hi everyone, I'm having some trouble sorting lists. I suspect this might have something to do with locale settings and/or character encoding/unicode. Consider the following example, text...
4
by: Brian Alexander | last post by:
Hello; I'm curious to know how people preserve exceptions that arise in a try ... finally block. Consider this example: try: getResource() doSomething() finally: alwaysFreeResource()
13
by: KefX | last post by:
This may have been discussed before, but I'm kind of confused as to why Python doesn't support having both an except ~and~ a finally clause, like this: try: raise RuntimeException except:...
9
by: David Stockwell | last post by:
In referring to my copy of the python bible, it tells me I can't use all three items 'try' except and finally. I can use the t/f or t/e combinations though What combination can i use if i want...
6
by: William Park | last post by:
(crossposted to comp.lang.python, because this may be of interest to them.) Python has try-block, within which you can raise exception. Once it's raised, execution breaks out of the try-block...
1
by: djw | last post by:
c.l.p- I am having trouble understanding how one is supposed to correctly utilize try:...except:...finally: in real code. If I have a block of code like: def foo(): try: ... some code that...
4
by: wk6pack | last post by:
Hi, I was wondering why when I declare the dim variable outside the try statement, I could use the .dispose() function but when I declare it inside the try statement, I get Name 'varname' is not...
3
by: Sori Schwimmer | last post by:
Hi, I think that would be useful to have an improved version of the "try" statement, as follows: try(retrys=0,timeout=0): # things to try except: # what to do if failed
2
by: Shi Mu | last post by:
very hard for me to understand the difference between try...except and try...finally
20
by: John Salerno | last post by:
I'm starting out with this: try: if int(text) 0: return True else: self.error_message() return False except ValueError: self.error_message()
1
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
0
by: veera ravala | last post by:
ServiceNow is a powerful cloud-based platform that offers a wide range of services to help organizations manage their workflows, operations, and IT services more efficiently. At its core, ServiceNow...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
0
by: mar23 | last post by:
Here's the situation. I have a form called frmDiceInventory with subform called subfrmDice. The subform's control source is linked to a query called qryDiceInventory. I've been trying to pick up the...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.