Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception treatment best practice

Tags:

c#

I would like to know which is the best way to make a Exception treatment, because inside my Try statement, I have a lot of validations, and if I get some Exception there, my Catch statement can tell me what happens, but how could I know in which field occurs the Exception ?

Sample Code

try
{
   // If I get a Exception when converting to number, 
   // I will understand the error 
   // but how could I know where in my `Try` statement was the error ?
   int valor = Convert.ToInt32(xmlnode[i].ChildNodes.Item(2).InnerText.Trim());
   // A Lot of another validations here
}
Catch(Exception e)
{
      this.LogInformation(e.Message);
}
like image 920
Lucas_Santos Avatar asked Feb 17 '23 00:02

Lucas_Santos


1 Answers

Best practises would be not to use Try-Catch at all when you convert strings to numbers. Therefore you should use the TryParse methods like int.TryParse.

// note that here is also a possible error-source
string valorToken = xmlnode[i].ChildNodes.Item(2).InnerText.Trim(); 
int valor;
if(!int.TryParse(valorToken, out valor))
{
    // log this
}
// else valor was parsed correctly

Apart from that, if you want to provide exact error messages you have to use multiple try-catch or handle different exception types (the most general Exception type must be the last).

like image 168
Tim Schmelter Avatar answered Feb 24 '23 04:02

Tim Schmelter