Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if there is an exception in the "using" will it be automatically closed

Tags:

c#

vb.net

Because I am using a "using" here, If there is an exception any where in the TRY will the FtpWebRequest, FtpWebRespons and responseStream automatically be closed?

Try
 Dim request As FtpWebRequest = CType(WebRequest.Create(""), FtpWebRequest)
        request.Method = WebRequestMethods.Ftp.ListDirectoryDetails

        request.Credentials = New NetworkCredential("", "")
        Using response As FtpWebResponse = CType(request.GetResponse(), FtpWebResponse)

            Using responseStream As Stream = response.GetResponseStream()
                Using reader As New StreamReader(responseStream)


                    TextBox1.Text = reader.ReadToEnd
                    TextBox1.Text += vbNewLine 
                    TextBox1.Text += vbNewLine
                    ' Use the + for appending (set the textbox to multiline)

                End Using

            End Using

        End Using    

Catch ex As Exception
     MessageBox.Show(ex.Message.ToString())
End Try
like image 716
Hello-World Avatar asked Nov 02 '12 16:11

Hello-World


3 Answers

Yes, all three will be closed.

The Using statement ends up calling the Dipose method on classes that implement IDisposable (this happens in a Finally section that the compiler generates). In this case, these classes will close when Dispose is called.

There are very few exceptions to this - if the process exits (say by calling Environment.Exit in the body of the Using statements), then the Finally block and disposal are not going to happen.

like image 107
Oded Avatar answered Nov 18 '22 16:11

Oded


Yes they will be disposed of except for when there is a Stack Overflow. From the documentation:

A Using block behaves like a Try...Finally construction in which the Try block uses the resources and the Finally block disposes of them. Because of this, the Using block guarantees disposal of the resources, no matter how you exit the block. This is true even in the case of an unhandled exception, except for a StackOverflowException.

like image 34
John Koerner Avatar answered Nov 18 '22 16:11

John Koerner


They will 'automatically' be disposed; if disposing closes a thing that can be opened, then yes.

like image 5
Grant Thomas Avatar answered Nov 18 '22 17:11

Grant Thomas