0

Is it possible to create a method/extension to try-catch a piece of code within some brachets? For example:

public static void TryCatchrep(//CODEHERE)
    {
        bool t;
        do
        {
            try
            {
                //CODEHERE
                t = true;
            }
            catch
            {
                //ERROR
                t = false;
            }
        } while (t == false); //Repeats on catch
        
    }
Shenpai
  • 3
  • 1
  • Well you could do this using a delegate that you put in the parameter so you just pass the function you wanna try/catch like following ```TryCatchrep(functionTotest)``` and that`s it. you understand? – Marcel Müller Aug 17 '20 at 09:39
  • I'd say yes, you can, the snippet you posted is (almost) working. What stops you from trying? what problem are you facing? – Gian Paolo Aug 17 '20 at 09:39
  • Not clear question. But if inside of the `try` block, should be catched. Calling function, expression, loop etc. –  Aug 17 '20 at 09:39
  • 2
    Does this answer your question? [Cleanest way to write retry logic?](https://stackoverflow.com/questions/1563191/cleanest-way-to-write-retry-logic) – Drag and Drop Aug 17 '20 at 09:40
  • 3
    Firstly, don't ever be afraid of declarative and readable code, Secondly, stop wanting to hide stuff behind magic functions, Thirdly, It looks like you are trying to control process flow by exceptions... Its best to check for the state if you can beforehand apposed to unwinding the stack. Lastly if you need retry logic, look into the defacto modern resilience and transient-fault-handling standard, *Polly* – TheGeneral Aug 17 '20 at 09:43

1 Answers1

7
public static void TryCatchrep(Action codeHere)
    {
        bool t;
        do
        {
            try
            {
                codeHere?.Invoke();
                t = true;
            }
            catch
            {
                //ERROR
                t = false;
            }
        } while (t == false); //Repeats on catch
        
    }

It would be called like this:

TryCatchrep(() => {
  // Do something
});
Jason
  • 1,505
  • 5
  • 9