Unexceptional exceptions (from C# 2.0 chat)
Earlier today, we had C# language chat which was well attended. Even a bunch of us together barely managed to answer the questions posted by C# developers about all sorts of things. Exceptions was one of the popular topics. Two questions caught my eye (paraphrased here)
1. Should I perf test an exception code path; and
2. Why don't you provide additional methods like System.IO.File.IsLocked() so that I can write more performant code
Let's start with the second one because it is more specific and illustrative. In a hurry, I answered that I will pass on the suggestion to the class library team. While discussing with a few members on that team, the problems with implementing the suggestions immediately came up:
Files are shared resources that are accessed concurrently. Just because File.IsLocked() returns false does not mean that when you attempt to do something with the file, you won't get an exception saying it is locked. You can't avoid the race condition here. So here is what would happen:
1. A few users may be able to use the check as a perf improvement and will actually still code defensively to handle the possibility of a rarer exception because the file is locked.
2. Many may be surprised to find that immediately after checking, the condition reverses. This could be a source of a latent bug.
3. Even after checking for a couple of common exceptions (oxymoron of sorts), other exceptions can still occur - so there is no way around defensive programming with try / catch / finally (https://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfUsingCatchFinallyTogether_PG.asp).
Unless it is possible to provide atomic operations that can handle multiple cases (e.g Upserts in databases) or some other critical section mechanism, such checks don't mean much. On the other hand, for your local variables, assuming that you have handled thread safety issues, you could do such checks: e.g. IsNull() makes more sense than IsLocked().
Do you have any other exceptional stories :-)?