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

try- catch

I'm new so bear with me. Is there a way for the catch to fix a problem
then start the try over again?

For example, I have this console application sync a remote database and it
takes hours. Sometimes the link, for no apparent reason will drop and will
trigger the catch. I want the catch to wait a minute then start the try
over again. Possible? or not?

Luke
Oct 27 '07 #1
8 3123
Sure. Just structure your code in such a way to support that. For example
if your oringal method looked like this:

void Foo()
{
<Do stuff>

Try {
<DoDB Stuff>
} catch {}

<Do More Stuff>
}

You could rewrite it like this:

void Foo()
{
<Do Stuff>
while (!DoDBStuff())
{
Thread.Sleep(1000);
}
<Do More Suff)
}

bool DoDBStuff()
{
try{
<DoDB Stuff>
return true;
} catch {
return false;
}
}

Note, you wouldn't want to do leave the while loop like that as it could
become an infinite loop. You'd most likely want to put some counter in
there to kick out of the loop after so many retries. You'd then need to
check to see if it ever succeeded and probably throw an exception instead
of "Doing more stuff" in the event that it never succeeded.

You also want to be careful with Thread.Sleep. It will let you pause before
resuming. However, if this is running in your main thread it will freeze
the applications UI as well.

--
Andrew Faust
andrew[at]andrewfaust.com
http://www.andrewfaust.com
"Luke Davis" <lu**@demnetworks.comwrote in message
news:eG**************@TK2MSFTNGP02.phx.gbl...
I'm new so bear with me. Is there a way for the catch to fix a problem
then start the try over again?

For example, I have this console application sync a remote database and
it takes hours. Sometimes the link, for no apparent reason will drop
and will trigger the catch. I want the catch to wait a minute then
start the try over again. Possible? or not?

Luke
Oct 27 '07 #2
Thanks,

After the Thread.sleep do I need to call foo() again? within foo?
"Andrew Faust" <an****@andrewfaust.comwrote in message
news:0A**********************************@microsof t.com...
Sure. Just structure your code in such a way to support that. For example
if your oringal method looked like this:

void Foo()
{
<Do stuff>

Try {
<DoDB Stuff>
} catch {}

<Do More Stuff>
}

You could rewrite it like this:

void Foo()
{
<Do Stuff>
while (!DoDBStuff())
{
Thread.Sleep(1000);
}
<Do More Suff)
}

bool DoDBStuff()
{
try{
<DoDB Stuff>
return true;
} catch {
return false;
}
}

Note, you wouldn't want to do leave the while loop like that as it could
become an infinite loop. You'd most likely want to put some counter in
there to kick out of the loop after so many retries. You'd then need to
check to see if it ever succeeded and probably throw an exception instead
of "Doing more stuff" in the event that it never succeeded.

You also want to be careful with Thread.Sleep. It will let you pause
before resuming. However, if this is running in your main thread it will
freeze the applications UI as well.

--
Andrew Faust
andrew[at]andrewfaust.com
http://www.andrewfaust.com
"Luke Davis" <lu**@demnetworks.comwrote in message
news:eG**************@TK2MSFTNGP02.phx.gbl...
>I'm new so bear with me. Is there a way for the catch to fix a problem
then start the try over again?

For example, I have this console application sync a remote database and
it takes hours. Sometimes the link, for no apparent reason will drop
and will trigger the catch. I want the catch to wait a minute then
start the try over again. Possible? or not?

Luke

Oct 27 '07 #3
In article <OB*************@TK2MSFTNGP06.phx.gbl"Luke
Davis"<lu**@demnetworks.comwrote:
Thanks,
After the Thread.sleep do I need to call foo() again? within foo?
No. Using the code he proposed, the method that is catching the
exception returns true or false depending on whether the exception
happened or not. The while() loop causes that method to be called
repeatedly until it returns true. That is sufficient for the purpose
of repeating the operation with a 1 second delay between attempts.

That said, there are any number of alternative means for accomplishing
this sort of thing. The suggestion was just one example. The general
idea is always going to be the same though: catching the exception
doesn't preclude you being able to go back and try the operation
again. The only requirement is that the try/catch block can't
intersection with flow-control statements, just as other kinds of
blocks in the code can't intersect with each other.

The only thing unusual about a try/catch block as compared to other
block constructs is that flow can jump from one block to the other
(but still only within the same try/catch clause). Other than that,
retrying an operation after it fails in a try/catch block is pretty
much exactly the same as you'd do it in any other context.

Pete

--
I'm trying a new usenet client for Mac, Nemo OS X.
You can download it at http://www.malcom-mac.com/nemo

Oct 27 '07 #4
No, because it's in a loop. Keep in mind that you won't want to implement
it exactly like this. I put out just a simple example to show the concept,
however, there are some issues you'd need to deal with. The biggest issue
is the fact that it can get in an infinite loop if DoDBStuff never
succeeds. In reality you should probably inspect the exception that was
thrown. Some exceptions like connection timeouts are acceptable to just
retry the operation. However, some exceptions may indicate an issue that
will cause it to never succeed. For example, if you were performing an
insert and you tried to set an Int field to 'Bob', that will obviously
always throw an exception no matter how many times you try it. I'd
recommend catching only the exceptions you want to retry and continue
throwing the insurmountable errors.

--
Andrew Faust
andrew[at]andrewfaust.com
http://www.andrewfaust.com
"Luke Davis" <lu**@demnetworks.comwrote in message
news:OB*************@TK2MSFTNGP06.phx.gbl...
Thanks,

After the Thread.sleep do I need to call foo() again? within foo?
"Andrew Faust" <an****@andrewfaust.comwrote in message
news:0A**********************************@microsof t.com...
>Sure. Just structure your code in such a way to support that. For
example if your oringal method looked like this:

void Foo()
{
<Do stuff>

Try {
<DoDB Stuff>
} catch {}

<Do More Stuff>
}

You could rewrite it like this:

void Foo()
{
<Do Stuff>
while (!DoDBStuff())
{
Thread.Sleep(1000);
}
<Do More Suff)
}

bool DoDBStuff()
{
try{
<DoDB Stuff>
return true;
} catch {
return false;
}
}

Note, you wouldn't want to do leave the while loop like that as it could
become an infinite loop. You'd most likely want to put some counter in
there to kick out of the loop after so many retries. You'd then need to
check to see if it ever succeeded and probably throw an exception
instead of "Doing more stuff" in the event that it never succeeded.

You also want to be careful with Thread.Sleep. It will let you pause
before resuming. However, if this is running in your main thread it will
freeze the applications UI as well.

--
Andrew Faust
andrew[at]andrewfaust.com
http://www.andrewfaust.com
"Luke Davis" <lu**@demnetworks.comwrote in message
news:eG**************@TK2MSFTNGP02.phx.gbl...
>>I'm new so bear with me. Is there a way for the catch to fix a
problem then start the try over again?

For example, I have this console application sync a remote database and
it takes hours. Sometimes the link, for no apparent reason will drop
and will trigger the catch. I want the catch to wait a minute then
start the try over again. Possible? or not?

Luke

Oct 27 '07 #5


"Luke Davis" <lu**@demnetworks.comwrote in message
news:eG**************@TK2MSFTNGP02.phx.gbl...
I'm new so bear with me. Is there a way for the catch to fix a problem
then start the try over again?

For example, I have this console application sync a remote database and it
takes hours. Sometimes the link, for no apparent reason will drop and
will trigger the catch. I want the catch to wait a minute then start the
try over again. Possible? or not?

Luke
You could just use a global flag. The method that calls this database
method should be made to wait.

You set the flag in the database method on its try/catch --- the catch and
you clear the Exception by setting it to null and come out of the method
back to the method that called it.

Since you cleared the Exception, if the method that made the call to the
database method had a try/catch in calling the database method, then it's
not going to take the catch path. It's going to comeback to the last line in
the try.

It's at this point in the try that you check for the flag. If the flag is
set, then you wait a minute and then you make the call to the database
method again ----- try it again. You might want to set some kind of count
and check the count and stop after so many retries.

Oct 27 '07 #6
On Oct 27, 2:26 am, "Luke Davis" <l...@demnetworks.comwrote:
I'm new so bear with me. Is there a way for the catch to fix a problem
then start the try over again?

For example, I have this console application sync a remote database and it
takes hours. Sometimes the link, for no apparent reason will drop and will
trigger the catch. I want the catch to wait a minute then start the try
over again. Possible? or not?

Luke
hi,
I alway use goto for this, this is probably the only place wher it is
ok to use goto (if you do not like goto at all pleas contact the
langauge-author)
below you will find a snippet
int nrOfTries=0;

//goto is used here to do up to max_nr_of_connection_retries
//to hide genneral network error
START:

SqlConnection result = new SqlConnection(ConnecectionString);
int connectionTimeoutWas=result.ConnectionTimeout;

try
{
result.Open();
string commandText="select 'TEST CONNECTION' ";
SqlCommand test= new SqlCommand(commandText, result);
test.CommandTimeout=2;
//we do not care about results , only to see if exception occures
test.ExecuteNonQuery();
}
catch(Exception e)
{
nrOfTries++;
result.Close();
result.Dispose();
if(nrOfTries<=MAX_NR_OF_TRIES_FOR_CONNECTION)
{
ErrorHandling.ExceptionFormater form= new
ErrorHandling.ExceptionFormater(e);
Notifications.Notify.Warning(result, "dead connection found in
getOpenConnection current try#"
+nrOfTries +Global.NEW_LINE+form.FormatedException);
goto START;
}
else
{
throw new ApplicationException("To many attempts made in
GetOpenConnection current try#"
+ nrOfTries, e);
}
}

//result.ConnectionTimeout=connectionTimeoutWas;
return result;

Oct 27 '07 #7
Thanks everyone for your support, I'll be trying all of these ideas to see
which one works the best in my situation.

As for the goto I thought it can only call a marker below itself, in your
example you're telling it to go to the top of the code and start over, I'm
not near the computer with those files on it right now to try it out, but
that can be done right?
"almir" <ka*****@gmail.comwrote in message
news:11*********************@y42g2000hsy.googlegro ups.com...
On Oct 27, 2:26 am, "Luke Davis" <l...@demnetworks.comwrote:
>I'm new so bear with me. Is there a way for the catch to fix a problem
then start the try over again?

For example, I have this console application sync a remote database and
it
takes hours. Sometimes the link, for no apparent reason will drop and
will
trigger the catch. I want the catch to wait a minute then start the try
over again. Possible? or not?

Luke

hi,
I alway use goto for this, this is probably the only place wher it is
ok to use goto (if you do not like goto at all pleas contact the
langauge-author)
below you will find a snippet
int nrOfTries=0;

//goto is used here to do up to max_nr_of_connection_retries
//to hide genneral network error
START:

SqlConnection result = new SqlConnection(ConnecectionString);
int connectionTimeoutWas=result.ConnectionTimeout;

try
{
result.Open();
string commandText="select 'TEST CONNECTION' ";
SqlCommand test= new SqlCommand(commandText, result);
test.CommandTimeout=2;
//we do not care about results , only to see if exception occures
test.ExecuteNonQuery();
}
catch(Exception e)
{
nrOfTries++;
result.Close();
result.Dispose();
if(nrOfTries<=MAX_NR_OF_TRIES_FOR_CONNECTION)
{
ErrorHandling.ExceptionFormater form= new
ErrorHandling.ExceptionFormater(e);
Notifications.Notify.Warning(result, "dead connection found in
getOpenConnection current try#"
+nrOfTries +Global.NEW_LINE+form.FormatedException);
goto START;
}
else
{
throw new ApplicationException("To many attempts made in
GetOpenConnection current try#"
+ nrOfTries, e);
}
}

//result.ConnectionTimeout=connectionTimeoutWas;
return result;

Oct 27 '07 #8
Lew
almir wrote:
I alway use goto for this, this is probably the only place wher it is
ok to use goto (if you do not like goto at all pleas contact the
langauge-author)
below you will find a snippet
I do not agree that this represents a valid use of goto; in particular it
should not be used for non-local exits from a block. That's the purpose of
throwing an exception in the first place. I rate this example of goto as an
antipattern.

Others have shown a better idiom for the OP's purpose.

As an exercise, in languages that support goto, I try to justify its use every
so often in some piece of code. Nearly always a better, more reliable, more
extensible, clearer idiom replaces it.

P.S., code posts are more readable if spaces are used to indent instead of TAB
characters. Two to four spaces per indent level is sufficient for Usenet.

--
Lew
Oct 27 '07 #9

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

Similar topics

39
by: Erlend Fuglum | last post by:
Hi everyone, I'm having some trouble sorting lists. I suspect this might have something to do with locale settings and/or character encoding/unicode. Consider the following example, text...
13
by: KefX | last post by:
This may have been discussed before, but I'm kind of confused as to why Python doesn't support having both an except ~and~ a finally clause, like this: try: raise RuntimeException except:...
7
by: Robert Brewer | last post by:
Alex Martelli wrote in another thread: > One sign that somebody has moved from "Python newbie" to "good Python > programmer" is exactly the moment they realize why it's wrong to code: > > ...
9
by: David Stockwell | last post by:
In referring to my copy of the python bible, it tells me I can't use all three items 'try' except and finally. I can use the t/f or t/e combinations though What combination can i use if i want...
26
by: djw | last post by:
Hi, Folks- I have a question regarding the "proper" use of try: finally:... Consider some code like this: d = Device.open() try: d.someMethodThatCanRaiseError(...) if SomeCondition: raise...
6
by: William Park | last post by:
(crossposted to comp.lang.python, because this may be of interest to them.) Python has try-block, within which you can raise exception. Once it's raised, execution breaks out of the try-block...
1
by: djw | last post by:
c.l.p- I am having trouble understanding how one is supposed to correctly utilize try:...except:...finally: in real code. If I have a block of code like: def foo(): try: ... some code that...
40
by: Steve Juranich | last post by:
I know that this topic has the potential for blowing up in my face, but I can't help asking. I've been using Python since 1.5.1, so I'm not what you'd call a "n00b". I dutifully evangelize on the...
4
by: wk6pack | last post by:
Hi, I was wondering why when I declare the dim variable outside the try statement, I could use the .dispose() function but when I declare it inside the try statement, I get Name 'varname' is not...
20
by: John Salerno | last post by:
I'm starting out with this: try: if int(text) 0: return True else: self.error_message() return False except ValueError: self.error_message()
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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:
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...
0
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,...
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...

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.