Ella Sharakanski
Ella Sharakanski

Reputation: 2773

Replace all exceptions from a class

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!

Upvotes: 0

Views: 124

Answers (2)

Mike Wideman
Mike Wideman

Reputation: 1

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.

Upvotes: 0

Jeff Prince
Jeff Prince

Reputation: 678

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.

Upvotes: 2

Related Questions