Groups | Blog | Home
all groups > c# > february 2004 >

c# : Exceptions


Joe Mayo [C# MVP]
2/7/2004 6:04:08 PM
[quoted text, click to view]

Hi C# Learner,

The NetworkStream class has a CanWrite property you can use to avoid an
IOException. While that helps, it doesn't necessarily mean you won't
receive other exceptions while writing. If you look at the documentation
for the Write method, it will show you what other exception types could be
thrown.

Looking at your code above gets my attention right away because you are
eating the exception. Now, if your program only cares whether you could
write or not and can recover appropriately, that is okay. However, you've
left yourself with no way of knowing what the problem really was and no way
to figure out how to fix the problem.

I would take a look at the list of exceptions that could be thrown by a call
to Write to see if there was a way, in your situation, to recover. Also,
consider adding some type of logging capability so you will have a record of
what happened. The MSDN Architecture Center has some pretty good guidance
on building applications and one of the Patterns and Practices guides focus
explicitly on Exception Management:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/exceptdotnet.asp

Joe
--
http://www.csharp-station.com

C# Learner
2/7/2004 10:18:37 PM
Is there a nicer way to write the following?

private static bool TryWriteToStream(NetworkStream ns, byte[] bytes,
int size)
{
bool result = true;

try {
ns.Write(bytes, 0, size);
} catch {
result = false;
}

return result;
}

I mean - is there a way of determining failure/success of writing to
the NetworkStream, without having to rely on an exception being raised
C# Learner
2/8/2004 1:30:22 AM
[quoted text, click to view]

Yes, in this case, the program only cares whether or not it can write
successfully.

It's actually a proxy server, that attempts to write back to the
client. If the server cannot write to the client, it should just
presume the client has disconnected and carry on with its duties.

[quoted text, click to view]

AddThis Social Bookmark Button