Home > Net >  C# Execute code only if other code was successful
C# Execute code only if other code was successful

Time:11-23

Say I have

Method1(); // might return error
Method2(); // should only be executed if previous line successful

I could use try and catch, however I still want errors to happen, I just don't want Method2() to be run if any errors occurred.

CodePudding user response:

There is a "template" for functions that looks like this:

bool TrySomething( out int returnValue )

which return true if successful and false if not. The returnValue is only valid if the returned bool is true. So you can use those like this:

if( TrySomething(out int someValue) )
{
     Method2( someValue );
}

Another approach would be if Method1 throws an exception:

try
{
    Method1();
    // If Method1 throws an exception, Method2 will not be executed.
    // The control flow will be redirected to the "next" catch block
    // that handles the exception type or if none of those exist crash 
    // the app.
    Method2();
}
catch(SomeException e)
{
    //Handle Exception
} 

So, even if you do not surround this with a try/catch block and Method1 throws, the control flow will not move on to execute Method2.

CodePudding user response:

As suggested by @ProgrammingLlama you should do something like this:

     try {
        MethodWithErrorOrException();
        MethodAfter();
     }
     catch (Exception) {
        // Handling
     }
     finally {
        MethodAlwaysCalled();
     }

Naturally MethodWithErrorOrException() should rise Exception.

Alternatively you have to use a return value to the method MethodWithErrorOrException() to understand if everything was successful, but it is not the most elegant solution.

CodePudding user response:

Make Method1 return false on error. Than you can use it like this:

if(Method1()){Method2();}

  • Related