Reputation: 1105
Is there a better way for handling exceptions ? Can I do the same thing but only with one try catch ?
Do I need to create my own exceptions class ?
try
{
firstname = bd["firstname"].ToString();
}
catch (KeyNotFoundException fe)
{
firstname = null;
}
try
{
lastname = bd["lastname"].ToString();
}
catch (KeyNotFoundException fe)
{
lastname = null;
}
try
{
phone = bd["phone"].ToString();
}
catch (KeyNotFoundException fe)
{
phone = null;
}
...
...
Upvotes: 2
Views: 98
Reputation: 11
firstname = Convert.ToString( bd["firstname"]);
lastname = Convert.ToString( bd["lastname"]);
phone = Convert.ToString(bd["phone"]);
Try Convert.ToString("string Value") method instend of .ToString() to avoid Exception.
Upvotes: 1
Reputation: 8646
If you want to use try catch blocks with minimum overhead, You can write all the code in one try block and write multiple catch blocks.
try
{
firstname = bd["firstname"].ToString();
lastname = bd["lastname"].ToString();
phone = bd["phone"].ToString();
}
catch (KeyNotFoundException fe)
{
firstname = null;
}
catch (KeyNotFoundException ex)
{
lastname = null;
}
catch (KeyNotFoundException xe)
{
phone = null;
}
Upvotes: 0
Reputation: 460340
Do not use exceptions for normal program flow if possible:
firstname = bd.ContainsKey("firstname") ? bd["firstname"] : null;
lastname = bd.ContainsKey("lastname") ? bd["lastname"] : null;
phone = bd.ContainsKey("phone") ? bd["phone"] : null;
or (assuming you are accessing a Dictionary
):
bd.TryGetValue("firstname", out firstname);
bd.TryGetValue("lastname", out lastname);
bd.TryGetValue("phone", out phone);
Upvotes: 5