Answer the question
In order to leave comments, you need to log in
How to write such an algorithm in c#?
try
{
//вариант 1
}
try
{
//если вариант 1 не удался, делать вариант 2
}
try
{
//если варианты 1 и 2 не удались , делать вариант 3
}
catch
{
//если никакой из вариантов не удался
}
try{
//вариант1
}
catch{
try{
//вариант2
}
catch{
try{
//вариант3
}
catch{
//если никакой из вариантов не удался
}
}
}
Answer the question
In order to leave comments, you need to log in
If you can remove these exceptions, can you really change them to if else?
if(method1()) {}
else if (method2()) {}
else if (method3()) {}
else {
// выполняется при неудаче во всех случаях
}
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
} ... )
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.
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 questionAsk a Question
731 491 924 answers to any question