There are, of course, circumstances in which it is normal to catch a specific exception and do nothing. Here's a trivial example:
public FileStream OpenFile(string path) { FileStream f = null; try { f = new FileStream(path, FileMode.Open, FileAccess.ReadWrite); } catch (FileNotFoundException) { } return f; }
You can also write a method as follows:
public FileStream OpenFile(string path) { FileStream f = null; FileInfo fi = new FileInfo(path); if (fi.Exists) { f = new FileStream(path, FileMode.Open, FileAccess.ReadWrite); } return f; }
In this case, catching the exception is (very) extremely safe, since the file can be deleted between the time it was checked for its existence and the time it was opened.
There are reasons to not do this, of course. In .NET, exceptions are expensive computational, so you want to avoid everything that throws a lot of them. (In Python, where exceptions are cheap, this is a common idiom for using exceptions to do things like breaking from loops.)
But this ignores the specific exception. This code:
catch { }
unforgivable.
There is no good reason not to catch the particular typed exception that the code in the try block is about to throw. The first reason a naive developer gives exceptions for exception, regardless of type: “But I don’t know what type of exception can be thrown,” is a kind of answer to the question.
If you do not know what type of exception can be thrown, you do not know how your code can fail. If you don’t know how your code may fail, you have no reason to believe that it will continue to process normally if this happens.
Robert Rossney Oct 15 '08 at 18:37 2008-10-15 18:37
source share