2

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; } ... ... 
1
  • it's a BsonDocument variable Commented Jul 18, 2013 at 9:37

3 Answers 3

5

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); 
Sign up to request clarification or add additional context in comments.

3 Comments

Since you have mentioned that bd is a BsonDocument you could replace ContainsKey with Contains.
Thank you Tim, I got ContainsValue, TryGetValue, TryGetElement what is the difference ?
@user2037696: I must admit that i have no experiences with mongodb, however, from the documentation it seems that you have to use Contains if you want to know if the dictionary contains the given key(so like ContainsKey). So TryGetValue seems to be equivalent to Dictionary.TryGetValue.
1

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.

Comments

0

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; } 

3 Comments

Using the same exception type in multiple catch blocks will not work: only the first will be run.
what if i have different exception objects?
Just checked: this is a compiler error (.NET 4.5/C#5). Use of different identifiers makes no difference.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.