473,779 Members | 1,952 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 #1
54 2905

"Stefan Arentz" <st***********@ gmail.com> wrote in message
news:87******** ****@keizer.soz e.com...

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?


Simple use a class with a destructor (it's because Java doesn't have
destructors that it needs finally)

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

The FooBusiness destructor does the cleanup. This way you do not even need a
try/catch

john
Jul 22 '05 #2

"Stefan Arentz" <st***********@ gmail.com> skrev i en meddelelse
news:87******** ****@keizer.soz e.com...
[snip] 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.


Hi Stefan

John Harrison has already answered your question. I just want to add that
you could check out boost for some of the smart pointers there. There is
also "scopeguard " for more special stuff.

/Peter
Jul 22 '05 #3
"John Harrison" <jo************ *@hotmail.com> writes:
Simple use a class with a destructor (it's because Java doesn't have
destructors that it needs finally)

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

The FooBusiness destructor does the cleanup. This way you do not even need a
try/catch


but what's about this:

void bar()
{
char * my_ptr;
try
{
SomeObject instace;
my_ptr = new char[987];
// do something
instace.doSomeh ting() // throws an exception let's say MyExec
// work with pointer
delete my_ptr
}
catch(MyExec &exc)
{
delete my_ptr;
// error handling
}
}

Here it's necessary to duplicate code, another example would be file
handling.
Sometimes a finally - block can help.

Mayby someone cann tell me why this was not taken into C++

Kind regards,
Nicolas

--
| Nicolas Pavlidis | Elvis Presly: |\ |__ |
| Student of SE & KM | "Into the goto" | \|__| |
| pa****@sbox.tug raz.at | ICQ #320057056 | |
|-------------------University of Technology, Graz----------------|
Jul 22 '05 #4
"Peter Koch Larsen" <pk*****@mailme .dk> writes:
"Stefan Arentz" <st***********@ gmail.com> skrev i en meddelelse
news:87******** ****@keizer.soz e.com...

[snip]
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.


Hi Stefan

John Harrison has already answered your question. I just want to add that
you could check out boost for some of the smart pointers there. There is
also "scopeguard " for more special stuff.


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

S.
Jul 22 '05 #5
"John Harrison" <jo************ *@hotmail.com> writes:

....
Simple use a class with a destructor (it's because Java doesn't have
destructors that it needs finally)

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

The FooBusiness destructor does the cleanup. This way you do not even need a
try/catch


I don't buy this for two reasons.

Wrapper classes introduce more code. I would like to use less code. I also
think it is a workaround and not a structural solution.

The above would simply move the exception handling and my finally problem
to a different place but it would still be present. I like it that you as
a user of the class don't have to deal with it anymore, but that is more
visual/convenience.

S.
Jul 22 '05 #6
* Nicolas Pavlidis:

but what's about this:

void bar()
{
char * my_ptr;
try
{
SomeObject instace;
my_ptr = new char[987];
// do something
instace.doSomeh ting() // throws an exception let's say MyExec
// work with pointer
delete my_ptr
}
catch(MyExec &exc)
{
delete my_ptr;
// error handling
}
}

void bar()
{
std::vector<cha r> my_ptr( 987 );
// do something
instace.doSomeh ting(); // semicolon here
}
Here it's necessary to duplicate code
Nope.

another example would be file handling.
Nope.

Sometimes a finally - block can help.
Yes.

Mayby someone cann tell me why this was not taken into C++


Because 'finally' is rarely needed in C++, and where it is needed it
indicates a redesign/refactoring is called for, and in the extremely
rare cases where that isn't an option, you can easily emulate it.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #7
al***@start.no (Alf P. Steinbach) writes:

....
Mayby someone cann tell me why this was not taken into C++


Because 'finally' is rarely needed in C++, and where it is needed it
indicates a redesign/refactoring is called for, and in the extremely
rare cases where that isn't an option, you can easily emulate it.


So how do you emulate it.

In my situation: no templates, no STL, no external libraries. Just bare
C++. GCC extensions are acceptable (3.3).

I've used inner functions (GCC extension) at one point.

void Foo()
{
vars;

void cleanup() {
cleanup vars;
}

try {
}

catch (...) {
cleanup();
throw;
}

cleanup();
}

But still, very yuckie :)

S.
Jul 22 '05 #8
On 21 Sep 2004 14:32:39 +0200, Stefan Arentz <st***********@ gmail.com>
wrote:

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).
So your current project isn't in standard C++, but rather a
company/personal dialect? I'm not sure we can help much with that...
//
// 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?


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

where the foo business uses stack based objects whose destructors do
the cleanup. If your company doesn't allow that, then your company is
using mackled C++, and might be better off with C# or Java. At the
very least you can use std::auto_ptr.

Tom
Jul 22 '05 #9
>
I'm on a device that is too small to even include STL :)


If you design your classes with nice d'tors and only use classes
instead of new/malloc allocations, the problem is void. If you seem to
have a small device (WTF is this - a fridge?), then write optimized
code. The 'final' keyword would not do anything else than wrap your
code in a gargabe collector, which _is_ available as template classes
for those who cannot remember what they allocate. ;)
A good compiler will produce smal code from a template library, though
the source code might be big. And don't tell me you're compiling the
program _on_ the fride.
-Gernot


Jul 22 '05 #10

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

Similar topics

0
1193
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
3083
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
4759
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
1357
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
9633
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
10305
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
10137
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
8959
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...
1
7483
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6724
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
5373
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
5503
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3632
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.