Ian

Ian

  • NA
  • 4
  • 0

try/catch best practice

Mar 13 2007 5:48 AM

I've never been certain of the best way to use try/catch statements. For instance, int.Parse throws three exceptions: ArgumentNullException, FormatException, OverflowException. Should I write code to catch all three of these exception types every time I call int.Parse?

Also, is it better to wrap every line of code which can generate an exception in it's own try/catch block or is it better to wrap several lines of code together.

And further, if I have the 2 lines of code which both throw the same exception should I place each line within it's own try/catch statements so that I know which line threw the exception? E.g.

try{
    int.Parse(s1);
    myHashTable.ContainsKey(s2);
}
catch(ArgumentNullException){
}

which line caused the exception?


try{
    int.Parse(s1);
}
catch(ArgumentNullException){
}

try{
    myHashTable.ContainsKey(s2);
}
catch(ArgumentNullException){
}

Now we know which line caused the exception but it is a little long winded.

Any advice on this would be greatly appreciated.


Answers (1)