thomsan
thomsan

Reputation: 483

How to resume second method after first method throws an exception C#

While looking on C# try catch tutorial, I got following question. My sample code as follows,

Inside mainMethod() , I need to call three separate methods. Inside testMethodOne(), I need to handle exception as. If testMethodOne() throws exception, without executing testMethodTwo(dt), mainMethod() throwing exception. I need to call testMethodTwo(dt); and testMethodThreee(dt); if testMethodOne() throws exception, how can I do it.

public void MainMethod(data dt){

    try{
    
    testMethodOne(dt);
    testMethodTwo(dt);
    testMethodThreee(dt);   
    
    }catch(Exception ex){
    
    
        throw ex;
    
    }
}

public void testMethodOne(dt){
    try 
    {
      //  Block of code to try
    }
    catch (Exception e)
    {
      //  Block of code to handle errors
    }
} 

Upvotes: 0

Views: 234

Answers (2)

Klaus Gütter
Klaus Gütter

Reputation: 11977

I understood your question as follows (but I might be wrong, your questions is not very clear):

Even if one of your testMethods throws an exception, you still want to continue in the normal program flow with the other methods. If at least one of the method failed, mainMethod could then report this as AggregateException.

public void MainMethod(data dt)
{
    var exceptions = new List<Exception>();

    try
    {
        testMethodOne(dt);
    }
    catch (Exception ex)
    {
        exceptions.Add(ex);
    }

    try
    {
        testMethodTwo(dt);
    }
    catch (Exception ex)
    {
        exceptions.Add(ex);
    }

    try
    {
        testMethodThreee(dt);   
    }
    catch (Exception ex)
    {
        exceptions.Add(ex);
    }

    if (exceptions.Count > 0)
    {
        throw new AggregateException(exceptions);
    }
}

Upvotes: 1

The Lemon
The Lemon

Reputation: 1391

It seems as if you want exceptions to alter the flow of your main method without breaking everything. One easy method is to make each 'testmethod' return a boolean.

public bool testMethodOne(dt){
    try 
    {
      //  Block of code to try
      return true;
    }
    catch (Exception e)
    {
      //  Block of code to handle errors
      return false;
    }
} 

Then in your main code you can go

if(!testMethodOne(dt))
    if(!testMethodTwo(dt))
        if(!testMethodThree(dt)) 
             //log that all methods failed

The above snippet would try each method until it finds one that succeeds. If that's not the behaviour you are looking for can you reword your question to make it clearer? If you want the opposite to happen just get rid of the ! and it will go until one fails. Alternatively you could put a throw in your catch statement in each of the testMethods, and that would stop execution once one is reached as well.

Upvotes: 0

Related Questions