473,327 Members | 1,967 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,327 software developers and data experts.

Exception Safe Guard

After reading Andrei Alexandrescu and Petru Marginean's
"Generic: Change the Way You Write Exception-Safe Code ¡ª Forever"
http://www.ddj.com/cpp/184403758

I borrow Boost.Function, which makes the implementation much simpler.

here goes the demo:

#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/noncopyable.hpp>

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace boost;

using namespace std;

struct Guard
: private noncopyable
{
Guard(function0<voidconst& op)
: op_(op), committed_(false) {}

void Commit() throw()
{
committed_ = true;
}

~Guard()
{
if (!committed_)
op_();
}

private:
bool committed_;
function0<voidop_;
};

struct Obj
{
void Rollback() const {
cout << "Committed, Now Rolling back" << endl;
}
};

void MayThrow() throw(int)
{
srand(time(0));
if (int r = rand() % 2)
throw r;
}

int main()
try
{
Obj obj;
Guard guard(bind(&Obj::Rollback, obj));

// do the stuffs, which may throw
MayThrow();

guard.Commit();
}
catch (int i)
{
cout << "Exception: i = " << i << endl;
}
catch (...)
{
cout << "Unknown Exception" << endl;
}

Any suggestion is welcomed, including coding style.
--
Thanks
Barry
Sep 4 '07 #1
2 2106
Barry wrote:
Michael DOUBEZ wrote:
Barry a (&crit :
After reading Andrei Alexandrescu and Petru Marginean's
"Generic: Change the Way You Write Exception-Safe Code !* Forever"
http://www.ddj.com/cpp/184403758
>
I borrow Boost.Function, which makes the implementation much
simpler. [snip: good to me]
>
void MayThrow() throw(int)
{
srand(time(0));
srand(time(NULL)) is fine provided you don't have more than one
call per

I thought in C++, always write 0 as null pointer.
here writing NULL is because srand is C function?

Many people prefer using 0, but NULL is perfectly standard and safe.
Also, 0 works just fine in C.

Brian
Sep 4 '07 #2
Michael DOUBEZ wrote:
Yes and if you want to demonstrate guard idiom, you should definitly not
use catch(...) otherwise the following code is enough:
Obj obj;
try
{
// do the stuffs, which may throw
MayThrow();
}
catch (int i)
{
//...
}
catch(..)
{
//...
}
obj.Rollback()

Here catch(...) allows a 'finaly like' system which is not the point.
Michael,
you miss the most important part here.
Maybe I should've written the code in this may to make it clearer

void Transact() throw(int)
{
Obj obj;
Guard guard(bind(&Obj::Rollback, obj));

// do the stuffs, which may throw
MayThrow();

// coming this far, nothing thrown, we commit the transaction
guard.Commit();
cout << "Transaction successful" << endl;

// no matter exception thrown or not
// guard will be destructed, ~Guard() will be called

// 1. if exception throw then committed_ must be false
// the roll back functor will be called
// 2. else roll back functor won't be called, as
// committed_ is true
}

int main()
{
try
{
Transact();
}
catch (int i)
{
}
}
--
Thanks
Barry
Sep 5 '07 #3

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

Similar topics

3
by: Scott Brady Drummonds | last post by:
Hello, all, My most recent assignment has me working on a medium- to large-sized Windows-based C++ software project. My background is entirely on UNIX systems, where it appears that most of my...
3
by: Lou | last post by:
I can't track down this exception. If anyone has any ideas, please pass them on. I've been trying to kill this bug for days now. An unhandled exception of type 'System.NullReferenceException'...
8
by: Robert Gravereaux | last post by:
I've noticed that the first exception thrown/caught by an app running in debug is very slow - it takes perhaps 7 or 8 seconds on my P4 machine. I've noticed this on several different machines...
14
by: Nenad Dobrilovic | last post by:
Hi, Is it possible for exception object to be aware of it's throwing? I want to log in the text file when exeption is thrown, not when the exception object is created (because I can create...
7
by: Dan Bass | last post by:
In a somewhat complex application, I've developed plug-in architecture and am having a problem as to when to catch general exceptions for logging purposes. In each plug-in class library, for...
24
by: Dan Bass | last post by:
I know that XslTransform's Transform is thread safe according to the MSDN, and that Load is not. I've therefore applied this simply Mutex to it and would just like to confirm this is okay. ...
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...
4
by: 6tc1 | last post by:
Hi all, I have just finished debugging a windows application and have solved the problem - however, I want to be sure that I understand the problem before I move on. Before I detail the problem,...
4
by: George2 | last post by:
Hello everyone, Here is Bjarne's exception safe sample, http://www.research.att.com/~bs/3rd_safe.pdf template <class Tclass Safe {
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.