473,803 Members | 2,807 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

The 'finally' debate


I was just reading through some old articles in the 'Why not develop new
language' thread and came across the finally debate.

Everytime I mention 'finally' to C++ programmers I get almost emotional
responses about why it is not needed in C++. I don't get that.

For example, consider the following code. Please note, I can only use
heap allocated objects in my current project (new/delete).

//
// Foo - Tries to foo. Can throw a FooException
//

void Foo()
{
try {
// Do your foo business that could throw a FooException
}

catch (...) {
// Cleanup your business
throw;
}

// Cleanup your business
}

Now, with finally I could do this:

void Foo()
{
try {
// Do your foo business that could throw a FooException
}

finally {
// Cleanup your business
}
}

Which I find *much* cleaner than the other example as there is no
need to do the cleanup twice.

Anyway, the debate is useless because we don't have finally. So my question
really is, how do people refactor the above to something nicer?

S.
Jul 22 '05
54 2909
Ioannis Vranos <iv*@guesswh.at .grad.com> wrote in
news:ci******** **@ulysses.noc. ntua.gr:
Jeff Flinn wrote:
It is "mandatory" if you want exception safe code. The above, without
"=0" is equivalent to:

char* my_ptr = rand();

Not exactly, but anyway.


Close enough.....
What happens if/when new throws?


What happens?


How about later in the catch block where my_ptr is attempted to be deleted?
If the variable is initialized to 0 first, then the catch block will be
able to delete it. Without the initialization, the delete would be
performed on an uninitialized pointer, resulting in UB.
Jul 22 '05 #41
> Well, it is code for firmware of a small device. Not very small, but small
enough that something like STL or Boost is not an option.


Not "all" Boost. Just look at the "scoped" smart pointers - two header
files. They are small, efficient, and any decent compiler will
optimize away all the overhead of using them.

BTW, long time ago I missed "finally" just as you do. Now, I consider
it a flaw in a programming language :)
Jul 22 '05 #42
Andre Kostur wrote:
How about later in the catch block where my_ptr is attempted to be deleted?
If the variable is initialized to 0 first, then the catch block will be
able to delete it. Without the initialization, the delete would be
performed on an uninitialized pointer, resulting in UB.

I assume, you mean that you perform many new operations in a large try
block with one catch (std::bad_alloc ) for all of them.

Too messy approach anyway.
What about definition upon use like:
char *p=new char[30];
// ...

char *something=new char[40];
In this case you can't make assumptions what has already been allocated
or not.

Both approaches above are not preferable. The best one is use a standard
library container on the stack when you want many objects and an object
alone in the stack if you want one object.

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #43
Rolf Magnus wrote:
Imho, an auto_ptr for
arrays should be part of the standard library.


Agreed. There should be something like std::auto_array <>, with
essentially identical semantics to auto_ptr, but using delete[] instead
of delete.
Jul 22 '05 #44
Rolf Magnus wrote:
Imho, an auto_ptr for
arrays should be part of the standard library.


I guess that the Committee decided that that the auto_ptr for arrays is
std::vector.
Jul 22 '05 #45
Ioannis Vranos <iv*@guesswh.at .grad.com> wrote in
news:ci******** **@ulysses.noc. ntua.gr:
Andre Kostur wrote:
How about later in the catch block where my_ptr is attempted to be
deleted? If the variable is initialized to 0 first, then the catch
block will be able to delete it. Without the initialization, the
delete would be performed on an uninitialized pointer, resulting in
UB.

I assume, you mean that you perform many new operations in a large try
block with one catch (std::bad_alloc ) for all of them.


.... or just one.
Too messy approach anyway.
Granted, we are assuming operations on plain pointers. Smart pointers
would probably be preferable. Helps to hide away this sort of
complexity.
What about definition upon use like:
char *p=new char[30];
Not exception safe (in the total context). Rewrite to:

char * p = 0;

p = new char[30];
// ...

char *something=new char[40];
Same here.
In this case you can't make assumptions what has already been
allocated or not.
With the appropriate re-writes, you don't care. You would only need:

catch( /* whatever */ )
{
delete[] something;
delete[] p;
}

Since in both cases, the pointers are initialized to 0 first (a nothrow
operation), whether the first new failed or the second new failed, it
doesn't matter. The pointers will either be a valid pointer (becuase the
new succeeded), or 0. In either case, calling delete[] on the pointer is
safe.
Both approaches above are not preferable. The best one is use a
standard library container on the stack when you want many objects and
an object alone in the stack if you want one object.


Not necessarily, as you may not have the stack space available to spare,
so heap allocations may be required. Or, there may be a requirement that
the objects be allocated in shared memory somewhere.
Jul 22 '05 #46
red floyd wrote:
Rolf Magnus wrote:

> Imho, an auto_ptr for
arrays should be part of the standard library.


I guess that the Committee decided that that the auto_ptr for arrays is
std::vector.


At one time std::vector did not need to guarantee that its controlled
objects were contiguous - hence inside an array. I don't know what loopholes
or changes have emerged since the Standard came out.

(However, semantically, you should only use arrays at an interface that
requires contiguity, and vector for everything else...)

--
Phlip
http://industrialxp.org/community/bi...UserInterfaces

Jul 22 '05 #47
Phlip wrote:
At one time std::vector did not need to guarantee that its controlled
objects were contiguous - hence inside an array. I don't know what loopholes
or changes have emerged since the Standard came out.

(However, semantically, you should only use arrays at an interface that
requires contiguity, and vector for everything else...)

Yes, although there is such a guarantee now. However prior to that, you
could still use iterators and operator[] to have a "sequential " access,
as with the rest containers.

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #48
Ioannis Vranos wrote:
Dietmar Kuehl wrote:
Correct, it is not mandatory. However, this "personal" style
reduces the potential for errors dramatically (not only in C++). As I have told many times in clc++, not really.
Well for starters, it would in the original code (corrected to
use appropriate delete operators):

char***my_ptr;
// at this point, my_ptr contains a random value
**try
**{
****my_ptr*=*ne w*char[987]; // if this new throws...
// other stuff
****delete[] my_ptr
**}
**catch(MyExec* &exc)
**{
// clean-up
****delete[]*my_ptr; // this expression is undefined
** // error handling goes here
}

Especially in the presence of hard to predict execution paths
uninitialized variables are hard to handle.
It also makes certain, IMO ill-advised, programming approachs,
like e.g. use of "try"-blocks, quite inattractive :-)

May you expand on that?


In general, it is easier to initialize a variable just once rather
than to assign it and later just change it without having read the
value. After all, the initialization would be wasted. If you attempt
to fold initialization with the assignment, i.e. initialize the
variable with the final value, in the above case with the value
returned from 'new', you will realize that you cannot do so prior to
the try-block (after all, it can throw and you want to handle the
error) nor within the try-block because you need the variable to do
the clean-up. The only viable approach becomes the use of a resource
management class - a good think, IMO.
--
<mailto:di***** ******@yahoo.co m> <http://www.dietmar-kuehl.de/>
<http://www.contendix.c om> - Software Development & Consulting
Jul 22 '05 #49
Stefan Arentz <st***********@ gmail.com> wrote:
"Gernot Frisch" <Me@Privacy.net > writes:

I'm on a device that is too small to even include STL :)

The device is a MIPS based device
with not too much RAM/Flash. Think <= 8MB. which needs to be shared
with a kernel, libraries some tools.


8MB ?! Here I was debating whether to use C++ (with STL) in a
device with 128K ram and 256K flash. Unfortunately the only
available C++ compilers were old, so they would not have proper
standard C++ support, and probably would be bad optimisers.
If the platform supported one of the 'mainstream' C++ compilers
(eg. Gnu, Intel, MS) it would have been a more serious option
(But I probably still would have stuck to C so that the code
could port to other devices which didn't have a good C++ compiler).
Jul 22 '05 #50

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

Similar topics

0
1194
by: melledge | last post by:
Worldwide Debate on Open Data Highlighted at XTech 2005 Presentation Topics Include Web Services, RSS, FOAF, OAI, Open Access, and More;Special Focus on OpenOffice.org's Influence on Standards and New Technologies Alexandria, Va. - April 20, 2005 - The opportunities and challenges of "open data" on the Web will be the focus of a new educational track at XTech 2005, the premier European conference for developers and managers working with...
23
3084
by: VB Programmer | last post by:
Variable scope doesn't make sense to me when it comes to Try Catch Finally. Example: In order to close/dispose a db connection you have to dim the connection outside of the Try Catch Finally block. But, I prefer to dim them "on the fly" only if needed (save as much resources as possible). A little further... I may wish to create a sqlcommand and datareader object ONLY if certain conditions are met. But, if I want to clean these up in the...
77
4769
by: berns | last post by:
Hi All, A coworker and I have been debating the 'correct' expectation of evaluation for the phrase a = b = c. Two different versions of GCC ended up compiling this as b = c; a = b and the other ended up compiling it as a = c; b = c. (Both with no optimizations enabled). How did we notice you may ask? Well, in our case 'b' was a memory mapped register that only has a select number of writable bits. He claims it has been a 'C...
2
1357
by: Wells | last post by:
Debate Simmering in US Over Regulation of Internet A heated debate is shaping up in Washington about a concept some activists are calling Internet network neutrality, known more popularly as net neutrality. At issue are calls for the U.S. government to regulate the Internet, and, in effect, opponents say, determine which companies get bigger shares of the profits. To read the full text, please go to:...
11
1361
by: John A Grandy | last post by:
I'm in a vigorous debate at my work regarding objects assuming knowledge of the type their containing object. This debate pertains specifically to ASP.NET, but I have decided to post in the C# forum because this is where most of the OO gurus hang out, and I view this as a fundamental issue of OO design. In ASP.NET, objects of type WebForm and UserControl have an intrinsic Page property which refers to their containing Page.
0
9703
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9565
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10550
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10317
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9125
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6844
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5501
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5633
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4275
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.