try and catch

G

Gary Wessle

Hi

I am using exceptions in my code and not sure how things are suppose
to work in my case.

while (1){
try
{
// call some methods here and use their side effect and returns.
break;
}
catch ( catch'm )
{
// something wicked happened.
}
}

Is this ok?
I mean, I keep on trying to do the task and break once it is done or
handle the error and get back to the same task again in case a throw
happens?

thanks
 
A

Alf P. Steinbach

* Gary Wessle:
Hi

I am using exceptions in my code and not sure how things are suppose
to work in my case.

while (1){
try
{
// call some methods here and use their side effect and returns.
break;
}
catch ( catch'm )
{
// something wicked happened.
}
}

Is this ok?

Well, it's a well-known pattern, but at the lowest possible level of
abstraction.

Note: if you don't use a counter or other loop variant, you risk an
infinite loop.

Also, to avoid silly-warnings from some compilers, better write
'for(;;)' than 'while(1)', even if the latter is an old C idiom.

I mean, I keep on trying to do the task and break once it is done or
handle the error and get back to the same task again in case a throw
happens?

Yeah, OK.

But if you have that low-level pattern occurring more than one place in
your code, consider abstracting it using the template pattern (nothing
to do with templates), like

const unsigned untilDoomsday = unsigned(-1);

struct Retry
{
bool operator( unsigned maxTries ) const
{
while( maxTries > 0 )
{
try
{
doIt();
return true;
}
catch( std::exception const& x )
{
onException( x );
}
if( maxTries != untilDoomsday ) { --maxTries; }
}
return false;
}

virtual void doIt() const = 0;
virtual void onException( std::exception const& x ) const {}
};

...
const bool succeeded = RetryDangerousThing()( untilDoomsday );

IIRC this was John Harrison's idea (not his code though, the above is
just scribbled down, guaranteed untouched by compiler's hands).
 
R

Rolf Magnus

Alf said:
But if you have that low-level pattern occurring more than one place in
your code, consider abstracting it using the template pattern (nothing
to do with templates), like

Well, it could be combined with templates. I don't really see a need for
runtime polymorphism here.
const unsigned untilDoomsday = unsigned(-1);

struct Retry
{
bool operator( unsigned maxTries ) const

ITYM:

bool operator()( unsigned maxTries ) const
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top