Can I make a method in C# to try-catch a line of code?

0 c#

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
        
    }
Run Code Online (Sandbox Code Playgroud)

Jas*_*son 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
        
    }
Run Code Online (Sandbox Code Playgroud)

It would be called like this:

TryCatchrep(() => {
  // Do something
});
Run Code Online (Sandbox Code Playgroud)