Pattern to search for various methods when throwing an exception

Here's a question to expose my lack of experience: I have a DoSomething () method that throws an exception if it fails to do this cleanly. If this fails, I try several times to use the less accurate DoSomethingApproximately () method in the hope that it will find a reasonably good solution; if this also fails, I finally call DoSomethingInaccurateButGuaranteedToWork () . All three are methods belonging to this object.

Two questions: first, is this a (admittedly ugly) template, or is there a more elegant way?

Secondly, what is the best way to keep track of how many times I called DoSomethingApproximately () , given that this could throw an exception? I am currently storing the iNoOfAttempt variable in an object, and the nested try blocks ... this is terrible and I'm ashamed.

+3
source share
4 answers

You should not use exceptions to control the flow of your application.

In your case, I combined the three methods together into one method and would return that particular approach, perhaps with an enumeration or something like that.

+4
source

Returns an error code instead of throwing an exception.

, , , , , .

   bool result = DoSomething();
   while (!result && tries < MAX_TRIES) {
       result = DoSomethingApproximately(); //This will increment tries
       if (tries > THRESHOLD) {
           result = DoSomethingThatAlwaysWorks();
       }
   }
+2

():

try{ return doSomething(); }
catch(ExpectedException) { ...not much here probably...}

for(i = 0 to RETRIES){
try{ return doSomethingApproximately; }
catch(ExpectedException) { ...not much here probably...}
}

doSomethingGuaranteed();

:

, , , . , , , . , , "" - ( ).

+2

. , LINQ.

Queue<Action> actions = new Queue<Action>(new Action[] {
   obj.DoSomething,
   obj.DoSomethingApproximately,
   obj.DoSomethingApproximately,
   obj.DoSomethingApproximately,
   obj.DoSomethingApproximately,
   obj.DoSomethingGuaranteed
});

actions.First(a => {
   try {
      a();
      return true;
   } catch (Exception) {
      return false;
   }
});
+2

Source: https://habr.com/ru/post/1697452/


All Articles