How to pass the next lines of execution when a catch error occurred in C #?

advertisements

In a function I am having several try - catch blocks like:

private void button1_click()
{
   try
   {
      // Lines of code
   }
   catch
   {
      // Lines of code
   }

   try
   {
      // Lines of code
   }
   catch
   {
      // Lines of code
   }
}

If any error occurs in catch block say 1st catch, I don't want the next lines of code to execute.

How do I skip the next try block statements on 1st catch error?


You would nest them, like this:

try
{
    //lines of code

    try
    {
        //lines of code
    }
    catch
    {
        //lines of code
    }
}
catch
{
    //lines of code
}

Alternatively, you could just use return in your first catch block:

try
{
    //lines of code
}
catch
{
    //lines of code
    return;
}

try
{
    //lines of code
}
catch
{
    //lines of code
}

Note that you have to be a little more thoughtful with the latter approach because if you're doing that in a method that needs to release resources (which you would do in a finally block), then the return would not accommodate that.