Brondahl
Brondahl

Reputation: 8597

Appropriate Exception to throw if you've manually detected a threading error

Suppose I write some multi-threaded C# code. (I know ... bad idea from the get-go ;) )

I have some code B, which I expect to only get called after code A has completed. I write and review my code carefully to convince myself that this is true, but I can't actually enforce that expectation, I can only check whether it is true.

So I put the checks in, and if the check ever fails, I want to throw and exception so that the developer gets a big shouty log message saying "Nope, ya fucked up; there's still an edge case where the threading doesn't do what you'd convinced yourself it did."

What's the best C# Exception type to throw here?

My instinct is to go with that old stand-by InvalidOperationException or possibly just a raw new Exception(message). But it would be nice if there were a slightly more specific type I could throw (like throwing an ArgumentException when that's the issue that's happened)

There are a few Exception types that auto-complete from Thread or Sync but they all look like they're intended for much deeper problems. i.e. there's something wrong with the actual threads. Here the thread are all fine ... it's the developer's threading logic that's in error.

Are there any sensible pre-existing Exception classes to use here?

Upvotes: 1

Views: 332

Answers (1)

Zohar Peled
Zohar Peled

Reputation: 82524

An InvalidOperationException is the most suitable built in exception for this situation.

See it's official documentation remarks section:

InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments. Typically, it is thrown when the state of an object cannot support the method call.

(emphasis mine).

Of course, there's nothing stopping you from creating your own Exception class if you want something more specific, but that would only make sense if you want the exception to carry information that doesn't fit inside the InvalidOperationException (and of course, if you do choose to create your own exception class, be sure to follow the guidlines in How to create user-defined exceptions:

  1. Derive from an existing Exception class
  2. use the word Exception as a suffix to the class name (MyVeryOwnSpecialException)
  3. Implement at least three public constructors:
    3.a: A constructor with no parameters
    3.b: A constructor that takes in a string message
    3.c: A constructor that takes in a string message and an Exception inner exception.

Upvotes: 4

Related Questions