D
D
dan-ver2014-06-30 22:52:55
C++ / C#
dan-ver, 2014-06-30 22:52:55

How to write such an algorithm in c#?

try
{
//вариант 1
}
try
{
//если вариант 1 не удался, делать вариант 2
}
try
{
//если варианты 1 и 2 не удались , делать вариант 3
}
catch
{
//если никакой из вариантов не удался 
}

I was thinking of doing something like this
try{
//вариант1
}
catch{
try{
//вариант2
}
catch{
try{
//вариант3
}
catch{
//если никакой из вариантов не удался 
}
}
}

but this is ... in general, tell me how you can make several exceptions in a row. Thanks

Answer the question

In order to leave comments, you need to log in

4 answer(s)
I
iamnothing, 2014-07-01
@dan-ver

If you can remove these exceptions, can you really change them to if else?

if(method1()) {}
else if (method2()) {}
else if (method3()) {}
else {
    // выполняется при неудаче во всех случаях
}

and in the methods method1, method2, method3, ... already implement your options and they return boolean

D
Deerenaros, 2014-07-01
@Deerenaros

In general, no way. Of course, you can build something like this zoo:

void tries(params Func<Void> bodies) {
  try {
    bodies[0]();
  } catch {
    tries(bodies.Skip(1).ToArray());
  }
}

// using
tries( () => {
    // first try
  }, () => {
    // second try if first failed
  }, () => {
    // third try if second after first failed
  } ... )

But @gleb_kudr and others are right - exceptions are far from being the best way to architect an application, and certainly should not be used to implement an algorithm. Although exceptions are quite cheap today (in C#, according to a small-scale policy, we already pay for exceptions without even using them), it is more logical to do the algorithm using branches, rather than exception handling. The only use-case I could come up with was a large number of different "same" resources with varying degrees of relevance - from the network to a request to insert a disk. Something like this. But all the same, these are exotic situations and it should be understood that exceptions are still exceptional situations and they should rarely be required. If the program successfully (perfectly) worked, but hundreds of exceptions were thrown, it's bad.

T
Terminaft, 2014-06-30
@Terminaft

What are you writing, since there is a possibility of such a heap of exceptions? It seems to me that all this can be replaced with ordinary if's.

G
gleb_kudr, 2014-07-01
@gleb_kudr

In general, "algorithm on exceptions" is a bad pattern with very poor performance. It is necessary to avoid the possible presence of "regular" exceptions.
Therefore - do if's, as mentioned in neighboring answers and use checks for null (the most common way to throw an exception is to refer to a non-existent object). If the nested chunks are large - pack each of them into a method or function - it will be easier to read.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question