Exception Handling Question

G

gz

Suppose I have the below code:

FileStream fs1 = new FileStream(...);
FileStream fs2 = new FileStream(...);

try
{
fs1.Write(...)
fs2.Write(...)
}
finally
{
if(fs1!=null)
fs1.Dispose();

if(fs2!=null)
fs2.Dispose();
}

My question is what happens if fs1.Dispose() throws an exception.
Maybe the disk is bad and it cannot successfully write the last piece
of buffer to it. If that happens, then:

1) Do I consider fs1 disposed?
2) Is it correct that fs2 is not Disposed?

In order for this to work, I have to write:

finally
{
try{
if(fs1!=null)
fs1.Dispose();
}
finally
{
if(fs2!=null)
fs2.Dispose();
}
}

This is very ugly, and incorrect. What happens if both fs1.Dispose()
and fs2.Dispose() throw exceptions?

Thanks,
gz
 
J

Jon Skeet [C# MVP]

gz said:
Suppose I have the below code:

FileStream fs1 = new FileStream(...);
FileStream fs2 = new FileStream(...);

try
{
fs1.Write(...)
fs2.Write(...)
}
finally
{
if(fs1!=null)
fs1.Dispose();

if(fs2!=null)
fs2.Dispose();
}

My question is what happens if fs1.Dispose() throws an exception.

Then fs2.Dispose doesn't get called. This is a good reason to use the
using statement:

using (FileStream fs1 = new FileStream(...))
using (FileStream fs2 = new FileStream(...))
{

}

Nested try/finally, and all is well.

(The exception would still get propagated, of course.)
 
G

gz

Then fs2.Dispose doesn't get called. This is a good reason to use the
using statement:

using (FileStream fs1 = new FileStream(...))
using (FileStream fs2 = new FileStream(...))
{

}

Nested try/finally, and all is well.

(The exception would still get propagated, of course.)

--
Jon Skeet - <[email protected]>http://www.pobox.com/~skeet  Blog:http://www.msmvps.com/jon.skeet
World class .NET training in the UK:http://iterativetraining.co.uk- Hide quoted text -

- Show quoted text -

Thanks for the response. I still have two questions:

1. If f1.Dispose() throws an exception, can I consider it is Disposed.
If not, what should I do?
2. If both f1.Dispose() and f2.Dispose() throw exceptions, which one
gets propagated?
 
J

Jon Skeet [C# MVP]

Thanks for the response. I still have two questions:

1. If f1.Dispose() throws an exception, can I consider it is Disposed.
If not, what should I do?

I certainly would.
2. If both f1.Dispose() and f2.Dispose() throw exceptions, which one
gets propagated?

Whichever throws last. The earlier exception (unfortunately) gets lost.
 
F

Family Tree Mike

I had never really thought about that before. If you look in MSDN, the
dispose method does not list any possible exceptions for the Dispose method,
as it would for known, throwable exceptions in other classes and methods.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top