C# Execute code only if other code was successful

C# Execute code only if other code was successful

Problem Description:

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.

Solution – 1

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 );

The various TryParse methods of different types are examples of that.

Another approach would be if Method1 throws an exception:

// 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.

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.

If you do use a try/catch block, Method2 will also not be executed:

    Method1(); // throws 
    Method2(); // won't execute
catch(SomeException ex)
    // Control flow will continue here.
    // Handle that exception
finally // optional
    // This will be executed regardless of whether there was an exception or not.

For further reading:

Solution – 2

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

     try {
     catch (Exception) {
        // Handling
     finally {

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.

Solution – 3

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


Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.