By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,786 Members | 1,131 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,786 IT Pros & Developers. It's quick & easy.

Try Catch Finally , pointers and Vb.net 2005 compiler warnings

P: n/a
Bob
Hi,
The compiler gives Warning 96 Variable 'cmdSource' is used before it has
been assigned a value. A null reference exception could result at runtime.

Dim cmdSource as SQlClient.SQLDataReader
Try
Set up the database read and do it.
Catch ex as system.exception
exception stuff here
Finally
cmdSource.close()
End try

Can't see a way out of this (Assuming a desire to explicity close in the
finally)
If you Dim inside the try statement you go out of scope in the finally.

Is there a tidy way to get rid of these warnings? My (was Vb.net 2003) Data
acccess class is now littered with them.
Thanks
Bob
Nov 21 '05 #1
Share this Question
Share on Google+
34 Replies


P: n/a
CT
Bob,

This will do the trick,

Dim cmdSource as SQlClient.SQLDataReader = Nothing

Alternatively, you can switch off this checking for a project, by opening
the Property Pages, clicking Compile tab, and clicking None on the
Notification list for the "Use of variable prior to assignment " condition.

--
Carsten Thomsen
Communities - http://community.integratedsolutions.dk

"Bob" <bo*@nowhere.com> wrote in message
news:uC**************@TK2MSFTNGP09.phx.gbl...
Hi,
The compiler gives Warning 96 Variable 'cmdSource' is used before it has
been assigned a value. A null reference exception could result at runtime.

Dim cmdSource as SQlClient.SQLDataReader
Try
Set up the database read and do it.
Catch ex as system.exception
exception stuff here
Finally
cmdSource.close()
End try

Can't see a way out of this (Assuming a desire to explicity close in the
finally)
If you Dim inside the try statement you go out of scope in the finally.

Is there a tidy way to get rid of these warnings? My (was Vb.net 2003)
Data
acccess class is now littered with them.
Thanks
Bob

Nov 21 '05 #2

P: n/a
Bob,

Dim cmdSource as SQlClient.SQLDataReader
Try
Set up the database read and do it.


Something as

dim cmdSource As SQLClient.SQLDataReader = cmd.ExecuteReader()
I hope this helps,

Cor


Nov 21 '05 #3

P: n/a
Carsten,

Dim cmdSource as SQlClient.SQLDataReader = Nothing


This is not the trick, it *hides* only the warning with an extra instruction
that has to be done.

In my opinion is better to correct for what is warned.

Cor
Nov 21 '05 #4

P: n/a
CT
Nope, it doesn't hide the warning. The warning is because the variable is
used prior to assignment.

"= Nothing" is the assignment... I'm sure I know what you're getting at,
i.e. use the ExecuteReader method, but why not do that in the Try block,
which is probably what is being done, and in that case, my solution will
work.

--
Carsten Thomsen
Communities - http://community.integratedsolutions.dk

"Cor Ligthert [MVP]" <no************@planet.nl> wrote in message
news:uQ**************@TK2MSFTNGP09.phx.gbl...
Carsten,

Dim cmdSource as SQlClient.SQLDataReader = Nothing


This is not the trick, it *hides* only the warning with an extra
instruction that has to be done.

In my opinion is better to correct for what is warned.

Cor

Nov 21 '05 #5

P: n/a
CT
That will only work if the ExecuteReader shouldn't be wrapped in a Try
block. Obviosuly, you can declare cmdSource inside the the Try block as
well, but what if you need access to it outside the Try block? Then you need
to move the declaration at the top, using Nothing as an assignment to avoid
the warning...

--
Carsten Thomsen
Communities - http://community.integratedsolutions.dk

"Cor Ligthert [MVP]" <no************@planet.nl> wrote in message
news:ur**************@tk2msftngp13.phx.gbl...
Bob,

Dim cmdSource as SQlClient.SQLDataReader
Try
Set up the database read and do it.


Something as

dim cmdSource As SQLClient.SQLDataReader = cmd.ExecuteReader()
I hope this helps,

Cor


Nov 21 '05 #6

P: n/a
"Bob" <bo*@nowhere.com> schrieb:
The compiler gives Warning 96 Variable 'cmdSource' is used before it has
been assigned a value. A null reference exception could result at runtime.

Dim cmdSource as SQlClient.SQLDataReader
Try
Set up the database read and do it.
Catch ex as system.exception
exception stuff here
Finally
\\\
If cmdSource IsNot Nothing Then
///
cmdSource.close()
\\\
End If
///
End try

Can't see a way out of this (Assuming a desire to explicity close in the
finally)
If you Dim inside the try statement you go out of scope in the finally.


I currently do not have VB 2005 at hand, thus I am not sure if it will cause
the warning to disappear.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Nov 21 '05 #7

P: n/a
Bob,
In addition to the other comments, consider using a Using statement instead.

http://msdn2.microsoft.com/en-us/lib...us,vs.80).aspx

Something like:

' VB 2005 syntax
Using cmdSource As SQLClient.SQLDataReader = cmd.ExecuteReader()
' process reader here...
End Using

As the Using statement does your Try/Finally with a check for not Nothing as
Herfried shows.

If you want to handle exceptions locally, then embed a Try/Catch.

' VB 2005 syntax
Using cmdSource As SQLClient.SQLDataReader = cmd.ExecuteReader()

| Try
' process reader here...
| Catch ex as system.exception
| exception stuff here
| End try
End Using

Normally I do not include the Try/Catch locally with the Using as above as I
use "global" Try/Catch blocks at a higher level then the read itself.

--
Hope this helps
Jay [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net
"Bob" <bo*@nowhere.com> wrote in message
news:uC**************@TK2MSFTNGP09.phx.gbl...
| Hi,
| The compiler gives Warning 96 Variable 'cmdSource' is used before it has
| been assigned a value. A null reference exception could result at runtime.
|
| Dim cmdSource as SQlClient.SQLDataReader
| Try
| Set up the database read and do it.
| Catch ex as system.exception
| exception stuff here
| Finally
| cmdSource.close()
| End try
|
| Can't see a way out of this (Assuming a desire to explicity close in the
| finally)
| If you Dim inside the try statement you go out of scope in the finally.
|
| Is there a tidy way to get rid of these warnings? My (was Vb.net 2003)
Data
| acccess class is now littered with them.
| Thanks
| Bob
|
|
Nov 21 '05 #8

P: n/a
Jay,

This was I missing from Herfried and why I did not tell it.
Normally I do not include the Try/Catch locally with the Using as above as
I
use "global" Try/Catch blocks at a higher level then the read itself.


In my opinion is that a must with a datareader where a connection can give
trouble.

:-)

Cor
Nov 21 '05 #9

P: n/a
Doh,

I thought Herfried had showed the using block here. He did not here probably
I saw him do that somewhere else, because I thought I had seen him doing
that. (I had the idea to show a sample with using here, however my problem
with the using is that you miss than the catch)

And as you probably know am I not so much a favorite for a global catch what
is than in my opinion a solution.

Just a preference.

Cor
Nov 21 '05 #10

P: n/a

"Bob" <bo*@nowhere.com> wrote in message
news:uC**************@TK2MSFTNGP09.phx.gbl...
Hi,
The compiler gives Warning 96 Variable 'cmdSource' is used before it has
been assigned a value. A null reference exception could result at runtime.

Dim cmdSource as SQlClient.SQLDataReader
Try
Set up the database read and do it.
Catch ex as system.exception
exception stuff here
Finally
cmdSource.close()
End try

With Try/Catch there is no reason to enter the Try block until you have
sucessfully opened the DataReader. On an exception before you have
initialized the DataReader does not require you to Dispose it.

dim cmdSource as SqlDataReader = cmd.ExecuteReader()
Try
'whatever
Catch ex as Exception
cmdSource.Dispose
throw
end try

In VB 2005 you should replace all these with Using blocks:

Using cmdSource As SqlClient.SqlDataReader = cmd.ExecuteReader()
'whatever
End Using
David
Nov 21 '05 #11

P: n/a
Cor,
| > Normally I do not include the Try/Catch locally with the Using as above
as
| In my opinion is that a must with a datareader where a connection can give
| trouble.

Why is the Catch "a must"?

I only include a Catch when there is something specific to do, such as
retrying the read. Logging the exception is not specific enough as the
global exception handlers (or a top level/main routine try/catch) can log
the error. However throwing a new exception with context information, such
as product id, is specific enough, as then the global exception handlers
would have more context sensitive information to display...
--
Hope this helps
Jay [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net
"Cor Ligthert [MVP]" <no************@planet.nl> wrote in message
news:Og**************@TK2MSFTNGP12.phx.gbl...
| Jay,
|
| This was I missing from Herfried and why I did not tell it.
|
| > Normally I do not include the Try/Catch locally with the Using as above
as
| > I
| > use "global" Try/Catch blocks at a higher level then the read itself.
|
| In my opinion is that a must with a datareader where a connection can give
| trouble.
|
| :-)
|
| Cor
|
|
Nov 21 '05 #12

P: n/a
Jay,
| In my opinion is that a must with a datareader where a connection can
give
| trouble.

Why is the Catch "a must"?

What do you do if you are reading 100000 rows and at 50000 the server goes
down?

I assume that the datareader is returning row by row and not one complete
resultset in a time, if that is the siutation than the catch is not
necessary.

Cor
Nov 21 '05 #13

P: n/a
Bob
Hi All,
Thanks for your replies.
I went with the inital assignment of both the command object and the
datareader to nothing.
I have also protected the disposals in the finally with a nothing test.
regards
Bob
"Bob" <bo*@nowhere.com> wrote in message
news:uC**************@TK2MSFTNGP09.phx.gbl...
Hi,
The compiler gives Warning 96 Variable 'cmdSource' is used before it has
been assigned a value. A null reference exception could result at runtime.

Dim cmdSource as SQlClient.SQLDataReader
Try
Set up the database read and do it.
Catch ex as system.exception
exception stuff here
Finally
cmdSource.close()
End try

Can't see a way out of this (Assuming a desire to explicity close in the
finally)
If you Dim inside the try statement you go out of scope in the finally.

Is there a tidy way to get rid of these warnings? My (was Vb.net 2003) Data acccess class is now littered with them.
Thanks
Bob

Nov 21 '05 #14

P: n/a
Cor,
| What do you do if you are reading 100000 rows and at 50000 the server goes
| down?
"Nothing", other then abort the entire transaction.

That's my point, there is nothing you really can do for the read itself,
other then cause what called the read to fail, & possibly cause what called
that & so on...
What do you do?

--
Hope this helps
Jay [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net
"Cor Ligthert [MVP]" <no************@planet.nl> wrote in message
news:ut**************@TK2MSFTNGP10.phx.gbl...
| Jay,
|
| > | In my opinion is that a must with a datareader where a connection can
| > give
| > | trouble.
| >
| > Why is the Catch "a must"?
| >
| What do you do if you are reading 100000 rows and at 50000 the server goes
| down?
|
| I assume that the datareader is returning row by row and not one complete
| resultset in a time, if that is the siutation than the catch is not
| necessary.
|
| Cor
|
|
Nov 21 '05 #15

P: n/a
Jay,

"Jay B. Harlow [MVP - Outlook]" <Ja************@tsbradley.net> schrieb:
As the Using statement does your Try/Finally with a check for not Nothing
as
Herfried shows.


I still think that the compiler is stupid.

\\\
Dim f As Form
Try
f = New Form()
Catch ex As Exception

' Warning 1: Variable 'f' is used before it has been assigned a
' value. A null reference exception could result at runtime.
If f IsNot Nothing Then
f.Dispose()
End If
End Try
///

The 'f' in front of 'IsNot' is underlined and the warning included as a
comment in the snippet above is shown. However, it's impossible that a
'NullReferenceException' can be thrown at this line.

I am not specialized in what a compiler is able to detect, but I think that
this warning is counterproductive. It leads people to write explicit
assignments ('Dim f As Form = Nothing'), which is not necessary because the
compiler adds the assignment automatically. If there was no 'Using'
statement in VB 2005, the code above is IMO pretty "good practice" and there
it should not cause any warnings.

Cases where a warning makes sense:

\\\
Dim f As Form
f.Show() ' Warning!
///

\\\
Dim f As Form
If False Then
f = New Form()
End If
f.Show() ' Warning!
///

Cases where a warning does not make sense:

\\\
Dim f As Form
If...Then
f = New Form()
End If
If f IsNot Nothing Then
f.Show() ' No warning!
End If
///

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Nov 21 '05 #16

P: n/a
Herfried,
| I am not specialized in what a compiler is able to detect, but I think
that
| this warning is counterproductive.
I agree, the little I've used this warning it seems very counter productive.
I suspect I will be turning it off in most of my projects.

I would think the "null warning" check should only be done when you are
accessing an instance member of the class.

I would not expect the warning when comparing the value with various
operators, including but not limited to: Is, IsNot, TypeOf, CType,
DirectCast, TryCast & other overloaded operators.

--
Hope this helps
Jay [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net
"Herfried K. Wagner [MVP]" <hi***************@gmx.at> wrote in message
news:ec**************@TK2MSFTNGP12.phx.gbl...
| Jay,
|
| "Jay B. Harlow [MVP - Outlook]" <Ja************@tsbradley.net> schrieb:
| > As the Using statement does your Try/Finally with a check for not
Nothing
| > as
| > Herfried shows.
|
| I still think that the compiler is stupid.
|
| \\\
| Dim f As Form
| Try
| f = New Form()
| Catch ex As Exception
|
| ' Warning 1: Variable 'f' is used before it has been assigned a
| ' value. A null reference exception could result at runtime.
| If f IsNot Nothing Then
| f.Dispose()
| End If
| End Try
| ///
|
| The 'f' in front of 'IsNot' is underlined and the warning included as a
| comment in the snippet above is shown. However, it's impossible that a
| 'NullReferenceException' can be thrown at this line.
|
| I am not specialized in what a compiler is able to detect, but I think
that
| this warning is counterproductive. It leads people to write explicit
| assignments ('Dim f As Form = Nothing'), which is not necessary because
the
| compiler adds the assignment automatically. If there was no 'Using'
| statement in VB 2005, the code above is IMO pretty "good practice" and
there
| it should not cause any warnings.
|
| Cases where a warning makes sense:
|
| \\\
| Dim f As Form
| f.Show() ' Warning!
| ///
|
| \\\
| Dim f As Form
| If False Then
| f = New Form()
| End If
| f.Show() ' Warning!
| ///
|
| Cases where a warning does not make sense:
|
| \\\
| Dim f As Form
| If...Then
| f = New Form()
| End If
| If f IsNot Nothing Then
| f.Show() ' No warning!
| End If
| ///
|
| --
| M S Herfried K. Wagner
| M V P <URL:http://dotnet.mvps.org/>
| V B <URL:http://classicvb.org/petition/>
|
Nov 21 '05 #17

P: n/a

"Herfried K. Wagner [MVP]" <hi***************@gmx.at> wrote in message
news:ec**************@TK2MSFTNGP12.phx.gbl...
Jay,

"Jay B. Harlow [MVP - Outlook]" <Ja************@tsbradley.net> schrieb:
As the Using statement does your Try/Finally with a check for not Nothing
as
Herfried shows.


I still think that the compiler is stupid.

\\\
Dim f As Form
Try
f = New Form()
Catch ex As Exception

' Warning 1: Variable 'f' is used before it has been assigned a
' value. A null reference exception could result at runtime.
If f IsNot Nothing Then
f.Dispose()
End If
End Try
///

The 'f' in front of 'IsNot' is underlined and the warning included as a
comment in the snippet above is shown. However, it's impossible that a
'NullReferenceException' can be thrown at this line.

I am not specialized in what a compiler is able to detect, but I think
that this warning is counterproductive. It leads people to write explicit
assignments ('Dim f As Form = Nothing'), which is not necessary because
the compiler adds the assignment automatically. If there was no 'Using'
statement in VB 2005, the code above is IMO pretty "good practice" and
there it should not cause any warnings.


No. The above code is and always was bad practice. Declaring local
variables without assigning them immediately is rarely the right thing to
do. Here the code should be:

Dim f As new Form()
Try
'use f
Catch ex As Exception

f.Dispose()
End Try

The Nothing check is not required because f is never Nothing. Only after
sucessfully instantiating a Form does the program need to enter the Try
block. Instantiating the Form inside the Try block only forces the extra
complexity of checking if it is _still_ nothing.

David
Nov 21 '05 #18

P: n/a
David,
Err, Oops...

Try:

| Dim f As new Form()
| Try
| 'use f

Finally

| f.Dispose()
| End Try

As you want to Dispose of the variable even if (*especially if*) an
exception is NOT thrown!

However I will continue to use the code Herfried showed (which is what VB
2005's Using statement creates) as sometimes the constructor itself may
throw the exception in which your code misses, while Herfried & the Using
statement catches.

Of course you could go with 2 Try statements, but that seems like
overkill...

--
Hope this helps
Jay [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net
"David Browne" <davidbaxterbrowne no potted me**@hotmail.com> wrote in
message news:OY**************@TK2MSFTNGP15.phx.gbl...
|
| "Herfried K. Wagner [MVP]" <hi***************@gmx.at> wrote in message
| news:ec**************@TK2MSFTNGP12.phx.gbl...
| > Jay,
| >
| > "Jay B. Harlow [MVP - Outlook]" <Ja************@tsbradley.net> schrieb:
| >> As the Using statement does your Try/Finally with a check for not
Nothing
| >> as
| >> Herfried shows.
| >
| > I still think that the compiler is stupid.
| >
| > \\\
| > Dim f As Form
| > Try
| > f = New Form()
| > Catch ex As Exception
| >
| > ' Warning 1: Variable 'f' is used before it has been assigned a
| > ' value. A null reference exception could result at runtime.
| > If f IsNot Nothing Then
| > f.Dispose()
| > End If
| > End Try
| > ///
| >
| > The 'f' in front of 'IsNot' is underlined and the warning included as a
| > comment in the snippet above is shown. However, it's impossible that a
| > 'NullReferenceException' can be thrown at this line.
| >
| > I am not specialized in what a compiler is able to detect, but I think
| > that this warning is counterproductive. It leads people to write
explicit
| > assignments ('Dim f As Form = Nothing'), which is not necessary because
| > the compiler adds the assignment automatically. If there was no 'Using'
| > statement in VB 2005, the code above is IMO pretty "good practice" and
| > there it should not cause any warnings.
| >
|
| No. The above code is and always was bad practice. Declaring local
| variables without assigning them immediately is rarely the right thing to
| do. Here the code should be:
|
| Dim f As new Form()
| Try
| 'use f
| Catch ex As Exception
|
| f.Dispose()
| End Try
|
| The Nothing check is not required because f is never Nothing. Only after
| sucessfully instantiating a Form does the program need to enter the Try
| block. Instantiating the Form inside the Try block only forces the extra
| complexity of checking if it is _still_ nothing.
|
| David
|
|
Nov 21 '05 #19

P: n/a

"Jay B. Harlow [MVP - Outlook]" <Ja************@tsbradley.net> wrote in
message news:uq*************@TK2MSFTNGP10.phx.gbl...
David,
Err, Oops...

Try:

| Dim f As new Form()
| Try
| 'use f

Finally

| f.Dispose()
| End Try

As you want to Dispose of the variable even if (*especially if*) an
exception is NOT thrown!


Yes, I didn't want to change the posted code, point out that variables
Disposables should be instantiated before the Try blocks in which they
disposed, not inside them.

David
Nov 21 '05 #20

P: n/a
Jay,
What do you do?


Be aware that I never used the using statement. However in this cases with a
datareader it can be (the change is low, however it is outside the process)
that the reading stops because of an exterior reason.

Think that you are making a long printing list and before the reading of the
last row it stops reading because of an hardware failure in the server and
the program goes down. Would you not want to tell to the user that not
everything is printed, although he could have the idea it was?

Another reason is than, that he not has directly to start again to try,
however first contact the administrator of that server.

Cor
Nov 21 '05 #21

P: n/a
David,

You spare me a message, I completly agree with you.

To show my opinion in this.

The only value reason I see not to do that is like this (and that does not
give a warning).
\\\
dim i as integer
try
'whatever code that needs a try
For i = 0 to 100
if i = 10 then exit
Next
Catch
end try
if i <> 10 then messagebox.show("something real strange hapened)
////

And for the rest I see no reasons to declare a variable outside its block
without assigning the object/value to it.

:-)

Cor
Nov 21 '05 #22

P: n/a
David,

On the other hand am I afraid that people are starting this kind of C#
practise standard.

dim myObjectT as myClassT = nothing

Just to avoid the warning.

This adds nothing, it only creates something more to suppress standard the
warning and has for the rest no sense at all. Than an option is better that
people don't want to see this kind of warnings.

Just my opinion.

Cor
Nov 21 '05 #23

P: n/a
"David Browne" <davidbaxterbrowne no potted me**@hotmail.com> schrieb:
As the Using statement does your Try/Finally with a check for not
Nothing as
Herfried shows.


I still think that the compiler is stupid.

\\\
Dim f As Form
Try
f = New Form()
Catch ex As Exception

' Warning 1: Variable 'f' is used before it has been assigned a
' value. A null reference exception could result at runtime.
If f IsNot Nothing Then
f.Dispose()
End If
End Try
///

The 'f' in front of 'IsNot' is underlined and the warning included as a
comment in the snippet above is shown. However, it's impossible that a
'NullReferenceException' can be thrown at this line.

I am not specialized in what a compiler is able to detect, but I think
that this warning is counterproductive. It leads people to write
explicit assignments ('Dim f As Form = Nothing'), which is not necessary
because the compiler adds the assignment automatically. If there was no
'Using' statement in VB 2005, the code above is IMO pretty "good
practice" and there it should not cause any warnings.


No. The above code is and always was bad practice. Declaring local
variables without assigning them immediately is rarely the right thing to
do. Here the code should be:


I have to disagree. Imagine we are not using a simple form but we are using
a database connection object. Creating the object could throw an exception.
In this case an additional 'Try...Catch' block + conditional execution of
the following code would be required, which increases complexity.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Nov 21 '05 #24

P: n/a
"Cor Ligthert [MVP]" <no************@planet.nl> schrieb:
On the other hand am I afraid that people are starting this kind of C#
practise standard.

dim myObjectT as myClassT = nothing
I fear this will occur in VB.NET! Some months ago I had a long and
controversial discussion in the German C# group, and I stated that I think
that this warning doesn't necessarily lead to better code. Well, you can
imagine what C# people replied ;-).
Just to avoid the warning.


Yep. That's why I think that it's very important that the compiler only
raises this warning in cases where it is 100 percent sure (decided at
compile time) that an exception will be thrown at runtime.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Nov 21 '05 #25

P: n/a
"Cor Ligthert [MVP]" <no************@planet.nl> schrieb:
Be aware that I never used the using statement. However in this cases with
a datareader it can be (the change is low, however it is outside the
process) that the reading stops because of an exterior reason.

Think that you are making a long printing list and before the reading of
the last row it stops reading because of an hardware failure in the server
and the program goes down. Would you not want to tell to the user that not
everything is printed, although he could have the idea it was?

Another reason is than, that he not has directly to start again to try,
however first contact the administrator of that server.


Well, imagine the data is a long list of customers in a company and the
reader fails at customer 50,000 out of 100,000. Would you display the
50,000 customers only? This could lead to serious problems, and it might be
better to simply make the user aware that an error occured and the
application is currently out of service.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Nov 21 '05 #26

P: n/a
Herfried,

Think that you are making a long printing list and before the reading of
the last row it stops reading because of an hardware failure in the
server and the program goes down. Would you not want to tell to the user
that not everything is printed, although he could have the idea it was?

Another reason is than, that he not has directly to start again to try,
however first contact the administrator of that server.


Well, imagine the data is a long list of customers in a company and the
reader fails at customer 50,000 out of 100,000. Would you display the
50,000 customers only? This could lead to serious problems, and it might
be better to simply make the user aware that an error occured and the
application is currently out of service.

--


That was what I tried to explain to Jay. I see that I did not succeed.

:-)))

Cor
Nov 21 '05 #27

P: n/a

"Herfried K. Wagner [MVP]" <hi***************@gmx.at> wrote in message
news:ew**************@TK2MSFTNGP10.phx.gbl...
"David Browne" <davidbaxterbrowne no potted me**@hotmail.com> schrieb:
As the Using statement does your Try/Finally with a check for not
Nothing as
Herfried shows.

I still think that the compiler is stupid.

\\\
Dim f As Form
Try
f = New Form()
Catch ex As Exception

' Warning 1: Variable 'f' is used before it has been assigned a
' value. A null reference exception could result at runtime.
If f IsNot Nothing Then
f.Dispose()
End If
End Try
///

The 'f' in front of 'IsNot' is underlined and the warning included as a
comment in the snippet above is shown. However, it's impossible that a
'NullReferenceException' can be thrown at this line.

I am not specialized in what a compiler is able to detect, but I think
that this warning is counterproductive. It leads people to write
explicit assignments ('Dim f As Form = Nothing'), which is not necessary
because the compiler adds the assignment automatically. If there was no
'Using' statement in VB 2005, the code above is IMO pretty "good
practice" and there it should not cause any warnings.


No. The above code is and always was bad practice. Declaring local
variables without assigning them immediately is rarely the right thing to
do. Here the code should be:


I have to disagree. Imagine we are not using a simple form but we are
using a database connection object. Creating the object could throw an
exception. In this case an additional 'Try...Catch' block + conditional
execution of the following code would be required, which increases
complexity.


No. The catch block should rethrow the exception. That _is_ conditional
execution of the following code.

But if creating the object throws an exception you don't have to dispose it.
The object creation belongs in a higher scope than its use and Dispose. But
big picture is that the using block should be used at every assignment of a
local variable to a Disposable type.

David
Nov 21 '05 #28

P: n/a
"David Browne" <davidbaxterbrowne no potted me**@hotmail.com> schrieb:
> As the Using statement does your Try/Finally with a check for not
> Nothing as
> Herfried shows.

I still think that the compiler is stupid.

\\\
Dim f As Form
Try
f = New Form()
Catch ex As Exception

' Warning 1: Variable 'f' is used before it has been assigned a
' value. A null reference exception could result at runtime.
If f IsNot Nothing Then
f.Dispose()
End If
End Try
///

The 'f' in front of 'IsNot' is underlined and the warning included as a
comment in the snippet above is shown. However, it's impossible that a
'NullReferenceException' can be thrown at this line.

I am not specialized in what a compiler is able to detect, but I think
that this warning is counterproductive. It leads people to write
explicit assignments ('Dim f As Form = Nothing'), which is not
necessary because the compiler adds the assignment automatically. If
there was no 'Using' statement in VB 2005, the code above is IMO pretty
"good practice" and there it should not cause any warnings.

No. The above code is and always was bad practice. Declaring local
variables without assigning them immediately is rarely the right thing
to do. Here the code should be:
I have to disagree. Imagine we are not using a simple form but we are
using a database connection object. Creating the object could throw an
exception. In this case an additional 'Try...Catch' block + conditional
execution of the following code would be required, which increases
complexity.


No. The catch block should rethrow the exception. That _is_ conditional
execution of the following code.


This strongly depends on the scenario.
But if creating the object throws an exception you don't have to dispose
it.
That's true. However, the construct I showed was not intended to be a
replacement for simple cases of 'Using' which are dealing with a single
object only. My main concern is about the uselessness of the compiler
warning.
The object creation belongs in a higher scope than its use and Dispose.
I believe it belongs to the same scope if possible. Higher scopes are
possible, but not always the best solution (minimum scope is often the best
choice, and in this particular case it's the same scope).

The main question is -- and this question has been discussed hundreds of
times -- whether or not the 'Try', 'Catch', and 'Finally' branches should
share the same scope.
But big picture is that the using block should be used at every
assignment of a local variable to a Disposable type.


The 'Using' block has IMO one big disadvantage: It introduces an additional
scope, although the 'Dispose' pattern has nothing to do with scopes.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Nov 21 '05 #29

P: n/a
David,
| Yes, I didn't want to change the posted code, point out that variables
| Disposables should be instantiated before the Try blocks in which they
| disposed, not inside them.
Sometimes, but not all the times!

Use ILDASM to look at the Using statement, the initialization code is inside
the Try block!

--
Hope this helps
Jay [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net
"David Browne" <davidbaxterbrowne no potted me**@hotmail.com> wrote in
message news:uy**************@tk2msftngp13.phx.gbl...
|
| "Jay B. Harlow [MVP - Outlook]" <Ja************@tsbradley.net> wrote in
| message news:uq*************@TK2MSFTNGP10.phx.gbl...
| > David,
| > Err, Oops...
| >
| > Try:
| >
| > | Dim f As new Form()
| > | Try
| > | 'use f
| >
| > Finally
| >
| > | f.Dispose()
| > | End Try
| >
| > As you want to Dispose of the variable even if (*especially if*) an
| > exception is NOT thrown!
| >
|
| Yes, I didn't want to change the posted code, point out that variables
| Disposables should be instantiated before the Try blocks in which they
| disposed, not inside them.
|
| David
|
|
Nov 21 '05 #30

P: n/a
Cor,
| the program goes down. Would you not want to tell to the user that not
| everything is printed, although he could have the idea it was?
Yes, my "global exception handlers" tell the user that not every thing
printed, as well as stop the printing itself.

As the Connection itself may have failed, the creation of the PrintDocument
may have failed, the creation of any number of System.Drawing objects may
have failed, any number of other things may have failed...

What I am saying is you don't need the *Catch* block by the read, you need
the *Finally* block by the read. As the *Finally* block is what cleans up
any resources that the read may have used.
--
Hope this helps
Jay [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net
"Cor Ligthert [MVP]" <no************@planet.nl> wrote in message
news:uF*************@TK2MSFTNGP09.phx.gbl...
| Jay,
|
| > What do you do?
|
| Be aware that I never used the using statement. However in this cases with
a
| datareader it can be (the change is low, however it is outside the
process)
| that the reading stops because of an exterior reason.
|
| Think that you are making a long printing list and before the reading of
the
| last row it stops reading because of an hardware failure in the server and
| the program goes down. Would you not want to tell to the user that not
| everything is printed, although he could have the idea it was?
|
| Another reason is than, that he not has directly to start again to try,
| however first contact the administrator of that server.
|
| Cor
|
|
Nov 21 '05 #31

P: n/a
Jay,
| the program goes down. Would you not want to tell to the user that not
| everything is printed, although he could have the idea it was?
Yes, my "global exception handlers" tell the user that not every thing
printed, as well as stop the printing itself.
I expressly have written that if you do use "using" in the situation of the
datareader (with an external server) you *need* the global exception
handlers as you wrote at the end of your message. That was the reason of my
first reply to you beside the other reason I found it important extra to
point on that.

see bellow
Normally I do not include the Try/Catch locally with the Using as above
as
I use "global" Try/Catch blocks at a higher level then the read itself.

In my opinion is that a must with a datareader where a connection can give
trouble.


I wrote as well that I did not like those global Try/Catch blocks and
therefore will not use the *using* in this kind of situations and therefore
need a Try Catch block.

I wrote as well that I could not give a good reasonable explanation why I do
not use them.

Probably I don't set it globally because that I find them to global from the
problem and don't give me that good feeling that every thing is catched.
Almost the same reason that I don't like to put more things globally.

Cor

Nov 21 '05 #32

P: n/a
Jay,
Use ILDASM to look at the Using statement, the initialization code is inside
the Try block!


Not on my machine (with beta 2). If that's really what you're seeing I
suggest you file a bug because it would violate the spec.
Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 21 '05 #33

P: n/a
Doh!
I really need to verify gradious statements. :-(

Below is from VB 2005 Beta 2 the initialize is outside the Try, however the
Finally still checks for Null/Nothing as the Try block could have set it to
nothing.

So now I'm left wondering where I saw it in IL that it was inside...
Private Sub About_Click(ByVal button As Office.CommandBarButton, ByRef
CancelDefault As Boolean)
Using dialog As New AboutBoxForm
dialog.ShowDialog()
End Using
End Sub
..method private instance void About_Click(class
[office]Microsoft.Office.Core.CommandBarButton button,
bool& CancelDefault) cil managed
{
// Code size 41 (0x29)
.maxstack 2
.locals init ([0] class XmlExportSample.AboutBoxForm dialog,
[1] bool VB$CG$t_bool$S0)
.language '{3A12D0B8-C26C-11D0-B442-00A0244A1DD2}',
'{994B45C4-E6E9-11D2-903F-00C04FA302A1}',
'{5A869D0B-6611-11D3-BD2A-0000F80849BD}'
// Source File 'C:\Documents and Settings\jay\My Documents\Visual Studio
2005\Projects\Xml Export Sample\Xml Export Sample\UIController.vb'
//000115: Private Sub About_Click(ByVal button As
Office.CommandBarButton, ByRef CancelDefault As Boolean)
IL_0000: nop
//000116: Using dialog As New AboutBoxForm
IL_0001: nop
IL_0002: newobj instance void XmlExportSample.AboutBoxForm::.ctor()
IL_0007: stloc.0
IL_0008: nop
//000117: dialog.ShowDialog()
.try
{
IL_0009: ldloc.0
IL_000a: callvirt instance valuetype
[System.Windows.Forms]System.Windows.Forms.DialogResult
[System.Windows.Forms]System.Windows.Forms.Form::ShowDialog()
IL_000f: pop
//000118: End Using
IL_0010: nop
IL_0011: leave.s IL_0027
} // end .try
finally
{
IL_0013: ldloc.0
IL_0014: ldnull
IL_0015: ceq
IL_0017: ldc.i4.0
IL_0018: ceq
IL_001a: stloc.1
IL_001b: ldloc.1
IL_001c: brfalse.s IL_0025
IL_001e: ldloc.0
IL_001f: callvirt instance void
[mscorlib]System.IDisposable::Dispose()
IL_0024: nop
IL_0025: nop
IL_0026: endfinally
//000119: End Sub
} // end handler
IL_0027: nop
IL_0028: ret
} // end of method UIController::About_Click

--
Hope this helps
Jay [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net
"Jay B. Harlow [MVP - Outlook]" <Ja************@tsbradley.net> wrote in
message news:e7**************@tk2msftngp13.phx.gbl...
| David,
|| Yes, I didn't want to change the posted code, point out that variables
|| Disposables should be instantiated before the Try blocks in which they
|| disposed, not inside them.
| Sometimes, but not all the times!
|
| Use ILDASM to look at the Using statement, the initialization code is
inside
| the Try block!
|
| --
| Hope this helps
| Jay [MVP - Outlook]
| .NET Application Architect, Enthusiast, & Evangelist
| T.S. Bradley - http://www.tsbradley.net
|
|
| "David Browne" <davidbaxterbrowne no potted me**@hotmail.com> wrote in
| message news:uy**************@tk2msftngp13.phx.gbl...
||
|| "Jay B. Harlow [MVP - Outlook]" <Ja************@tsbradley.net> wrote in
|| message news:uq*************@TK2MSFTNGP10.phx.gbl...
|| > David,
|| > Err, Oops...
|| >
|| > Try:
|| >
|| > | Dim f As new Form()
|| > | Try
|| > | 'use f
|| >
|| > Finally
|| >
|| > | f.Dispose()
|| > | End Try
|| >
|| > As you want to Dispose of the variable even if (*especially if*) an
|| > exception is NOT thrown!
|| >
||
|| Yes, I didn't want to change the posted code, point out that variables
|| Disposables should be instantiated before the Try blocks in which they
|| disposed, not inside them.
||
|| David
||
||
|
|
Nov 21 '05 #34

P: n/a
Mattias,
As I just posted: I verified after the fact and you are correct its not in
Beta 2.

I remember seeing the initialize inside someplace, but now I really don't
remember where.

--
Hope this helps
Jay [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net
"Mattias Sjögren" <ma********************@mvps.org> wrote in message
news:%2****************@TK2MSFTNGP09.phx.gbl...
| Jay,
|
| >Use ILDASM to look at the Using statement, the initialization code is
inside
| >the Try block!
|
| Not on my machine (with beta 2). If that's really what you're seeing I
| suggest you file a bug because it would violate the spec.
|
|
| Mattias
|
| --
| Mattias Sjögren [MVP] mattias @ mvps.org
| http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
| Please reply only to the newsgroup.
Nov 21 '05 #35

This discussion thread is closed

Replies have been disabled for this discussion.