0

I have 3 Methods, I am try catch for every method. If an error occur in Third method it goes to exception.

private void M1()
{  
   try
   {
     //some code
     //calling M2()
     //some code
   }
   catch(Exception ex)
   {
      MessageBox.Show(ex.Message);
   }
}
private void M2()
{  
   try
   {
     //some code
     //calling M3()
     //some code
   }
   catch(Exception ex)
   {
      throw ex;
   }
}
private void M3()
{  
   try
   {
     //some code
     //Error Occur
     //some code
   }
   catch(Exception ex)
   {
      throw ex;
   }
}

Now it goes directly to M1() method and shows Exception. And the another method is

private void M1()
{  
   try
   {
     //some code
     //calling M2()
     //some code
   }
   catch(Exception ex)
   {
      MessageBox.Show(ex.Message);
   }
}
private void M2()
{  
   try
   {
     //some code
     //calling M3()
     //some code
   }
   catch(Exception ex)
   {
      MessageBox.Show(ex.Message);
      return;
   }
}
private void M3()
{  
   try
   {
     //some code
     //Error Occur
     //some code
   }
   catch(Exception ex)
   {
      MessageBox.Show(ex.Message);
      return;
   }
}

After exception also it execute the code in M2() and in M1().

Which Program is best...,

sree aneev
  • 141
  • 4
  • 5
  • 18
  • 4
    First of all, don't catch an exception if you don't do anything with it. So this is bad practise: `catch(Exception ex) { throw ex; }`. If you want to keep the original stacktrace, you should at least use `throw` instead of `throw ex`. http://msdn.microsoft.com/en-us/library/seyhszts.aspx and http://stackoverflow.com/questions/4761216/c-throwing-custom-exception-best-practices – Tim Schmelter Mar 07 '13 at 12:10
  • None of them. 1) Catching an exception only to re-throw it -> no point, 2) Message boxes in non-UI methods -> bad separation of logic and presentation. – Thorsten Dittmar Mar 07 '13 at 12:12
  • Addendum: The reason why catching exceptions only to throw them again is bad practice, is because exception handling is **extremely** slow. – Nolonar Mar 07 '13 at 12:13
  • @Nolonar: Exception handling is only extremely slow in debug mode, in release mode it's just slow. – Guffa Mar 07 '13 at 12:15
  • 1
    don't use throw ex, use only throw. Instead of catching and throwing exception directly catch the exception in the main method (M1), that's better option. – nRk Mar 07 '13 at 12:18
  • I use throw it is good..., – sree aneev Mar 07 '13 at 12:29
  • which program is best in which **sense** ?? – tariq Mar 07 '13 at 12:32
  • I am a Learner..,In Programmer Sense.., – sree aneev Mar 07 '13 at 12:49

1 Answers1

2

There is nothing good or bad design, only your scenario decided the best approach.

If you want to catch the error on M1 then don't write Try .. catch in M2 and M3.

If you want to handle the error in the function where error was raised then put the Try .. catch in same function.

Romil Kumar Jain
  • 20,239
  • 9
  • 63
  • 92