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.
IanPosted Mar 13, 2007, 6:12 AM
I have 2 questions regarding your example:
1. Why include the line - int d = 0; within the try/catch block? Shouldn't you just target the lines that can cause an exception to be thrown?
2. I've been told in the past that you should never catch Exception because you don't know what the exception will be and therefore how do you know how to handle it. What do you think?