Click here to Skip to main content
15,890,690 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi,

Can anybody tell me how to handle errors inside procedure which calls other procedures in C#

In the following example, were do i use try catch block.

I need to stop and exit from P1 if any error occurs any were in the called procedures.

if we have
C#
private void P1()
{
P2();
P3();
....
}

private void P3() 
{
P4();
...
...

}

private void P4()
{
}


Thanks
Nirmala
Posted
Updated 13-Apr-14 1:56am
v2

Add error handlers in method P1.
For e.g.
C#
private void P1()
{
  try
  {
    P2();
    P3();
  ....
  }
  Catch (Exception ex)
  {
    //Handler
  }
}

Any errpr in P2, P3 or P4 will rollover to the parent handler.
 
Share this answer
 
v2
Comments
Manas Bhardwaj 13-Apr-14 8:01am    
You beat me. +5!
Abhinav S 13-Apr-14 11:42am    
Thank you.
It very much depends on what is happening in those function, where you want to handle the errors, and if you just want to log the error and move on to the next row/transaction/whatever. If you don't handle an error in (say) P4 then the error will be thrown up to the calling function, if you don't handle it there it will go up to the function calling that one and so on.

There are some articles on best practices for error handling on the following links

http://msdn.microsoft.com/en-us/library/seyhszts(v=vs.110).aspx[^]
Exception Handling Best Practices in .NET[^]
http://codebuild.blogspot.co.uk/2012/01/15-best-practices-about-exception.html[^]

[EDIT] Just had another thought. We often see code in QA here along the lines of
C#
try
{
    P1();
}
catch (Exception)
{
    //do nothing
}

This is worse than not having any error handling as the exception is just "swallowed" and you will never know whether your program worked. Don't do this
 
Share this answer
 
v2
If you don't do any error handling, any error which occurs in P2(), P3() or P4() would be propagated to the caller in the stack. Thus, in case of any error if you just want to exit, you don't have to do any thing extra in this example.

However, I would suggest to add some sort of logging or other exception handling in the main method (assuming P1 in this case) so that it can give you details later while debugging or trouble shooting.

Thus:

C#
private void P1()
{
    try
    {
        P2();
        P3();
    }
    catch(Exception exception)
    {
        //Log or handle this exception
    }
}

private void P3()
{
    P4();
}

private void P4()
{
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900