Occasionally I have a need to retry an operation several times before giving up. My code is like:
int retries = 3;
while(true) {
try {
DoSomething();
Or how about doing it a bit neater....
int retries = 3;
while (retries > 0)
{
if (DoSomething())
{
retries = 0;
}
else
{
retries--;
}
}
I believe throwing exceptions should generally be avoided as a mechanism unless your a passing them between boundaries (such as building a library other people can use). Why not just have the DoSomething()
command return true
if it was successful and false
otherwise?
EDIT: And this can be encapsulated inside a function like others have suggested as well. Only problem is if you are not writing the DoSomething()
function yourself