1

I've encountered a situation where due to some other area of code I called failing to copy a Dictionary<TKey, TValue> that it returns, a concurrency problem ensues: the Dictionary appears to contain illegal null keys.

I've fixed the underlying bug, but to help identify this issue should it crop up again in the future I'm adding a bit of code that explicitly checks for the null key in the loop that processes the returned dictionary and throws before things go any further. I'm not sure which exception class to throw, or which one to subclass if I'm defining a new one.

Community
  • 1
  • 1
Jeffrey Hantin
  • 35,734
  • 7
  • 75
  • 94

2 Answers2

6

Does any caller expect the exception? Can any caller handle the exception? Can any caller recover from the exception? What do you imagine is going to happen after the throw?

In this situation where data structures are arbitrarily corrupted pretty much none of your invariants are known to be true. The fact that you're still running code at all is a miracle. Unless you have a good reason to do otherwise I'd be inclined to log any info necessary to diagnose the bug and fail fast. Throwing an exception and running finally blocks is unlikely to make anything better.

Ultimately of course anything you do is a stopgap. Fix the bug that is corrupting your data.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • 2
    I *have* fixed the bug. I guess what I'm asking here is what to do if I discover that I'm already screwed -- this is basically an assertion failure situation. Log it and `Environment.FailFast()`? – Jeffrey Hantin Dec 17 '10 at 02:07
  • Grr, Compact Framework. `Process.GetCurrentProcess().Kill()` will have to do instead of `Environment.FailFast()`. – Jeffrey Hantin Dec 17 '10 at 02:21
0

I think that IllegalStateException should be ok. I understand that you should focus en make your code better so you don't run into this kind of situations.

But I faced a similar issue with a DTO which will find with no proper initialization because the actual object on the data base was lacking some data. Then, when retrieving the object and trying to use it we catch the IllegalStateException exception and we didn't use it, while at the same time we sent the error to the log so it can be fixed later.

Andres Farias
  • 2,683
  • 2
  • 13
  • 9