473,399 Members | 3,106 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,399 software developers and data experts.

is such exception handling approach good?

200 100+
Hello everyone,


Suppose I have some objects created on local function stack (not on heap). And I allocate and free all the related resources in the constructor and destructor (e.g. memory and file handles). And I do not implement explicit exception handling code in the function for resource free purpose, and simply rely on destructor to free resources if exception occurs, that is,

1. when exception occurs and the exception triggers us to go out of current function stack to the caller to find exception handlers;
2. since objects are allocated on local stack, when exception triggers us to go out of current stack to its caller to find exception handler, the lifecycle of local objects on local stack will expire, and its related destructor will be invoked and free resources.

Pseudo code like this,

Expand|Select|Wrap|Line Numbers
  1. void func()
  2. {
  3.       Class1 inst1;
  4.       Class2 inst2;
  5.  
  6.       ... // some operations
  7.  
  8.       return;
  9. }
  10.  
Does above code always safe? Are there any potential risks to leak resources?


thanks in advance,
George
Dec 21 '07 #1
6 1487
weaknessforcats
9,208 Expert Mod 8TB
This code is never safe.

When an exception is thrown, the current stack frame is not cleaned up. That is, the destructors for the local objects are not called.

That is, an exception is a hard go-to-the-catch-block.

This means you can't just willy-nilly use exceptions. You need to design for them. In your example, the two stack objects should be allocated on the heap. Then inside the function you catch the exception, delete the objects, and then rethrow it now that the local stack frame is cleaned up:

Expand|Select|Wrap|Line Numbers
  1. void func()
  2. {
  3.     Class1* inst1 = 0;
  4.     Class2* inst2 = 0;
  5.     try
  6.     {
  7.      inst1 = new Class1;
  8.      inst2 = new Class2;
  9.  
  10.       // some operations
  11.       throw 25;
  12.     }
  13.     catch (...)
  14.     {
  15.         delete inst1;
  16.         delete inst2;
  17.         throw;       //rethrow the excpetion
  18.     }
  19.       return;
  20. }
  21.  
Dec 21 '07 #2
George2
200 100+
Thanks weaknessforcats,


1.

I think we are talking about different things. :-)

This is your code,

Expand|Select|Wrap|Line Numbers
  1.     Class1* inst1 = 0;
  2.     Class2* inst2 = 0;
  3.      inst1 = new Class1;
  4.      inst2 = new Class2;
  5.  
This is my code

Expand|Select|Wrap|Line Numbers
  1.     Class1 inst1;
  2.     Class2 inst2;
  3.  
My object instances are on the stack, but your object instances are on the heap (only pointer on stack). I think in my situation, it is safe and does not leak any resources if there are any exception thrown when stack unwinding makes us go out of the stack, the destructor is automatically called (since when we are out of the current stack during stack unwinding, the lifecycle of inst1 and inst2 expired and their destructors are called).

2. what do you mean the stack is not cleaned up?

I think in my situation the destructors are called since during stack unwinding, the lifecycle of objects' instances are expired and their destructors should be called.

This code is never safe.

When an exception is thrown, the current stack frame is not cleaned up. That is, the destructors for the local objects are not called.
Please feel free to correct me if I am wrong.


regards,
George
Dec 22 '07 #3
weaknessforcats
9,208 Expert Mod 8TB
I think in my situation the destructors are called since during stack unwinding, the lifecycle of objects' instances are expired and their destructors should be called.
Yes, I was incorrect. I meant to say that heap allocations are not unwound in the current stack frame. Stack objects will have destructors call provided the exception is caught. Otherwise, they're not. Heap allocations will remain unless you delete them.

I so seldom use stack objects because of the risks associated with them when used as function arguments. It's too easy for a reference or an address of one of these stack objects to become a member of another object that is returned. Later, that reference or address may be no good and crash the program.
Dec 22 '07 #4
George2
200 100+
Thanks weaknessforcats,


I understand your points now. I think using auto_ptr can solve this issue when you forget to call delete explicitly, right?

Do you agree using auto_ptr and put cleanup code in destructor can solve all the issues?

Yes, I was incorrect. I meant to say that heap allocations are not unwound in the current stack frame. Stack objects will have destructors call provided the exception is caught. Otherwise, they're not. Heap allocations will remain unless you delete them.

I so seldom use stack objects because of the risks associated with them when used as function arguments. It's too easy for a reference or an address of one of these stack objects to become a member of another object that is returned. Later, that reference or address may be no good and crash the program.

regards,
George
Dec 24 '07 #5
weaknessforcats
9,208 Expert Mod 8TB
I think using auto_ptr can solve this issue when you forget to call delete explicitly, right?

Do you agree using auto_ptr and put cleanup code in destructor can solve all the issues?
Avoid using auto_ptr. It doesn't work like you think. See Effective STL by Scott Meyers Item #8.

However, the approach is correct. Use a smart pointer with built-in reference counting. There is an article I wrote in the Howtos for C++ on Handle classes. In that article is a template for a reference-counted handle that you are free to use in your applications. It works very like the shared_ptr that's coming out with the new C++.
Dec 24 '07 #6
George2
200 100+
Thanks weaknessforcats,

1.

Avoid using auto_ptr. It doesn't work like you think. See Effective STL by Scott Meyers Item #8.
Why in my sample, I can not use auto_ptr to solve this issue to make sub-components' destructor called automatically? More descriptions please?

2. I am interested in your article, could you post a link please?

However, the approach is correct. Use a smart pointer with built-in reference counting. There is an article I wrote in the Howtos for C++ on Handle classes. In that article is a template for a reference-counted handle that you are free to use in your applications. It works very like the shared_ptr that's coming out with the new C++.

regards,
George
Dec 25 '07 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

11
by: adi | last post by:
Dear all, This is more like a theoretical or conceptual question: which is better, using exception or return code for a .NET component? I had created a COM object (using VB6), which uses...
42
by: cody | last post by:
public DateTime Value { get { try { return new DateTime(int.Parse(tbYear.Text), int.Parse(tbMonth.Text), int.Parse(tbDay.Text)); } catch (FormatException)
1
by: Abelardo Vacca | last post by:
Hello, I am currently in the process of switching our application to a N-Tier model with .NET. One of the aspects we want ot get right from the start not to worry about it after is the...
28
by: Frank Puck | last post by:
Meanwhile there are at least 8 years that compilers exist, which provide a working implementation of C++ Exception Handling. Has anything changed meanwhile? From my point of view nothing has...
7
by: Julia | last post by:
Hi I have a system which composed from 2 different components 1.MailSender 2.MailReciever the Name of my system is JuliaSystem
44
by: craig | last post by:
I am wondering if there are some best practices for determining a strategy for using try/catch blocks within an application. My current thoughts are: 1. The code the initiates any high-level...
3
by: Bruce One | last post by:
I am developing a new project in which we should have a good Exception Handling. Ive seen there is a Exception Handling App Block in Enterprise Library, also I could use the Try-Catch structure...
14
by: Rex | last post by:
Re: Looking for Tips/Writeup on overall approach to Exception Processing Hi All - I am fairly new to C# and am wondering how to best implement (overall) Exception Processing within my...
3
by: George2 | last post by:
Hello everyone, Suppose I have some objects created on local function stack (not on heap). And I allocate and free all the related resources in the constructor and destructor (e.g. memory and...
35
by: eliben | last post by:
Python provides a quite good and feature-complete exception handling mechanism for its programmers. This is good. But exceptions, like any complex construct, are difficult to use correctly,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.