0

Is there a way in C# to replace all the ObjectDisposedException thrown by an instance of a NetworkStresm with MyException?

The purpose of this is that I want to read and write the stream while other threads may dispose it. And that's just fine - when the stream is disposed the exception is thrown and I handle it and it's part of the normal flow of the program (since the client may just disconnect). As opposed to other ObjectDisposedException of other objects that are really an error, a bug in my code.

So if I could make the stream throw MyException instead of the regular ObjectDisposedException, I could treat it differently.

Any other suggestions to accomplish this purpose are good as well.

Thanks!

Ella Sharakanski
  • 2,683
  • 3
  • 27
  • 47
  • Perhaps a better solution would be not to share the object between threads, ensure each thread has it's own instance of the `IDisposable` object and have each thread control when its own instance is disposed. Then you know when you get a `ObjectDisposedException` it is always a bug – Ben Robinson Sep 01 '15 at 17:16
  • Exceptions should never be part of the "normal flow" of a program, exceptions happen because something exceptional took place, don't use exceptions for control flow, it will lead to horrible headaches later. – Ron Beyer Sep 01 '15 at 17:27
  • @Ron Beyer If the client suddenly closes the stream it is both exceptional (I did not control it and I wish it didn't happen) and normal (it's not a bug in my code and I should consider it can happen). For real exceptional exceptions I close everything, restart and log the whole trace. For normal exceptions I just log a nice little warning – Ella Sharakanski Sep 01 '15 at 17:55
  • @Ben Robinson It still means that when the client disconnects and I write the stream (for example) an exception will be thrown. And then either I would have to try catch every read/write or again try catch in the main function and not know whether the exception is because the client has disconnected – Ella Sharakanski Sep 01 '15 at 18:02

2 Answers2

2

I think if you want that to happen you are going to have to catch ObjectDisposedException and rethrow MyException.

A better alternative (if you control the code you are calling) is to have the code on the other side check if it is already disposed and not throw ObjectDisposedException, but just return without doing anything.

Jeff Prince
  • 658
  • 6
  • 13
0

I'm not aware of any way to do this, but you might be able to achieve similar behavior by using the ObjectName property of the ObjectDisposedException to handle all of the exceptions thrown by a NetworkStream and rethrow the rest.

  • Thanks. I thought about it but the problem is, what if later I will create another stream that should have the regular behavior? Also this feels very hacky – Ella Sharakanski Sep 01 '15 at 17:49