Question about Using

J

Jack Jackson

I want to open a filestream and so some processing. If the open
throws an exception I want to throw a custom exception. If any other
exception occurs during the processing I want that exception to bubble
up.

The code without Using would be:

dim fs As IO.FileStream

try
fs = IO.File.Open(parmFileName, IO.FileMode.Create)
catch
<<Throw custom exception>>
end try

<< Code that writes using fs>>

fs.close()
fs.Dispose()


The only thing I can think of is this, but it seems kludgy to me:

Dim rethrow As Boolean = False
Try
Using fs = IO.File.Open(parmFileName, IO.FileMode.Create)
rethrow = True
<<Processing>>
fs.Close()
End Using
Catch
If rethrow
Throw
End If
<<Throw custom exception>>
End Try
 
T

Tom Shelton

I want to open a filestream and so some processing. If the open
throws an exception I want to throw a custom exception. If any other
exception occurs during the processing I want that exception to bubble
up.

The code without Using would be:

dim fs As IO.FileStream

try
fs = IO.File.Open(parmFileName, IO.FileMode.Create)
catch
<<Throw custom exception>>
end try

<< Code that writes using fs>>

fs.close()
fs.Dispose()

The only thing I can think of is this, but it seems kludgy to me:

Dim rethrow As Boolean = False
Try
Using fs = IO.File.Open(parmFileName, IO.FileMode.Create)
rethrow = True
<<Processing>>
fs.Close()
End Using
Catch
If rethrow
Throw
End If
<<Throw custom exception>>
End Try

It sounds as if you may not want to use a using block here. By the
way, if you do use using, calling fs.Close () inside is completly
redundant - since it will be called by dispose anyway.

You might want to do something like:

Dim fs As FileStream

Try
fs = File.Open (....)
Catch ex As Exception
Throw New CustomException (ex) ' you should set the inner exception
to the original :)
End Try

Try
' do cool stuff with fs
Finaly
fs.Close ()
End Try
 
J

Jack Jackson

It sounds as if you may not want to use a using block here. By the
way, if you do use using, calling fs.Close () inside is completly
redundant - since it will be called by dispose anyway.

You might want to do something like:

Dim fs As FileStream

Try
fs = File.Open (....)
Catch ex As Exception
Throw New CustomException (ex) ' you should set the inner exception
to the original :)
End Try

Try
' do cool stuff with fs
Finaly
fs.Close ()
End Try

That seems like the best solution. I was just thinking that I should
use the new whiz-bang Using.
 

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