C # Should I lock up to a complete exception?

I want to go once through the loop, but only if the exception is sent back through the loop. How can I write this in C #?

thanks

+6
c # loops
source share
6 answers

Sounds like a bad idea, but try something like this anyway:

bool exceptionthrown = false; while (!exceptionthrown) { try { // Do magic here } catch (Exception) { exceptionthrown = true; throw; } } 
+1
source share

It smells of bad design for me. General rule: exceptions should not be used for flow control. There are a number of reasons for this; namely, there are usually better / more reliable methods that can be used to test things before exceptions are thrown, and also reduces efficiency.

However, just for the sake of argument, you can do something like the following:

 while (true) { try { // do stuff here } catch (MyException) { continue; } // all is good break; } 

Again - this is not recommended. I would be happy to offer something better if you could provide a little more context / examples /

+19
source share

How about the following, where you can set the number of attempts:

  int tryCount = 0; while (tryCount < 3) { try { someReturn = SomeFunction(someParams); } catch (Exception) { tryCount++; continue; } break; } 
+2
source share

It really depends on what you are doing and on the type of exception. Many exceptions are not something that would be fixed just by trying again with the same inputs / data, and thus the loop will just throw an ad infinitum exception.

Instead, you should check the relevant exceptions and then process them accordingly for those specific exceptions.

+1
source share

Why not call a function that actually executes the loop, and after it there will be a catch that will call the function again.

 private void loop() { for(...) { } } 

any other method:

 try { loop(); } catch(Exception e) { loop(); } 
0
source share

Something like:

 bool done = false; while( ! done ) { try { DoSomething(); done = true; } catch(Exception ex) { HandleException(ex); } } 

As Noldorin said, it smells of poor design. You use exceptions to control program flow. It is better to have explicit checks of conditions that force you to repeat the operation.

0
source share

All Articles