Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try catch bad programming practice

Tags:

c#

try-catch

I am executing a stored procedure and returning a string. The string is set to return 1,0 or "USER DOES NOT EXISTS" depending on the conditions.

Just wanted to know if the following is a bad programming practice.

string result = _db.GetParameterValue(cmdObj, "@strMessage").ToString();
try
{
    int a = int.Parse(result);
    if (a == 1)
        Console.WriteLine("A");
    else
        Console.WriteLine("B");
}
catch
{
    Console.WriteLine(result);
}

Console.WriteLine(result);
like image 661
Rain Avatar asked Mar 01 '26 01:03

Rain


1 Answers

It is always better to specifically match rather than presume it was "USER NOT EXISTS" based on catching a failed int parse.

It is always bad practice to try/catch/swallow. If you're going to catch an exception, log it or throw.

You've not specified a language, so presuming it's C#, int.TryParse() is much cleaner than int.Parse inside a try/catch.

like image 104
robrich Avatar answered Mar 03 '26 13:03

robrich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!