Reputation: 2298
In my code:
private void cbbMaoDeObra_TextChanged(object sender, EventArgs e)
{
try
{
int resultado = Convert.ToInt32(cbbMaoDeObra.SelectedValue);
if (resultado == 0)
{
btnConfirmar.Enabled = false;
}
else
{
ViewStateWorkLogger = ViewStateWorkLogger.AbleToConfirm;
}
MaoDeObra = resultado;
}
catch (Exception)
{
return;
}
}
I have a try-catch to deal with some errors. My dynamic program, when started, will have a variable of type string
in cbbMaoDeObra and when it starts, this string is just 'letters' and can't be parsed. SelectedValue. This is because just after some events I initialize it and read from de Database. Then, without workarounds like I did up, like using return or leave the field empty, how can I deal with these errors?
Is try { statement } catch { empty }
recommended to be used?
Upvotes: 1
Views: 109
Reputation: 223257
Generally for parsing string values, the safer option is int.TryParse
. This will not raise the exception, instead it will return a bool
indicating success or failure.
if(int.TryParse("123", out resultado))
{
//parsing successful
}
else
{
// invalid input
}
but since SelectedValue
is of type object, you can use Convert.ToIn32
and safeguard against exception (with try-catch), or convert your SelectedValue to string and then use int.TryParse
.
string str = cbbMaoDeObra.SelectedValue as string;
if (str != null && int.TryParse(str, out resultado))
{
}
Is try { statement } catch { empty } recommended to be used?
There are very few places where empty catch would be useful. See: Is there any valid reason to ever ignore a caught exception.
Don't use catch(Exception)
, catch specific exception first, log/handle it. See Best Practices for Exceptions
Upvotes: 3