Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Variable scope and try and catch
Message
 
 
À
17/09/2003 17:20:08
Information générale
Forum:
ASP.NET
Catégorie:
Autre
Divers
Thread ID:
00829818
Message ID:
00830122
Vues:
26
Plamen,
Thank you very much for clarifying it for me and for detailed explanation. I got it now.

>You misunderstood me, Dmitry. You can rely on variable, "initialized" in Try, also in Catch and in Finally (I moved closing of SqlDataReader into Finally, because it's right place is in Finally). But in Catch and in Finally you have to check whether "initialization" in Try was successful (because instancing can also fail due to low memory or exception in execution engine):
>
>SqlConnection cnn;
>try
>{
>	cnn = new SqlConnection("Some connection string here");
>	cnn.Open();
>}
>catch(Exception ex)
>{
>	if (cnn != null)
>		MessageBox.Show(cnn.State.ToString());
>}
>finally
>{
>	if (cnn != null)
>		cnn.Close();
>}
>
>The one problem in previous code is that it will not compile, because it uses (only in Catch - it will be executed before Finally, so you get only one error and no two) cnn for comparison (cnn != null) before it is "initialized" (in C# compiler's terminology - there is no assignment to this variable before it is used for the first time). This is because compiler assumes that code execution can run into Catch block also if first row in Try block fails and in this case cnn will remain unassigned. So changing declaration to:
>
>SqlConnection cnn = null;
>
>will prevent this. I called this "initialization", because:
>
>cnn = new SqlConnection("Some connection string here");
>
>i call "instancing".
>
>Because VB. NET automatically "initializes" variables to default value, specific for every type (0 for Integer, Nothing for Object and so on), in VB .NET these two rows are equivalent:
>
>Dim cnn As SqlConnection
>Dim cnn As SqlConnection = Nothing
>
>(Nothing is equivalent to C#'s null). This is the reason for successful compiling of previous code (translated to VB .NET) without errors and without "initializing" of cnn to Nothing.
"The creative process is nothing but a series of crises." Isaac Bashevis Singer
"My experience is that as soon as people are old enough to know better, they don't know anything at all." Oscar Wilde
"If a nation values anything more than freedom, it will lose its freedom; and the irony of it is that if it is comfort or money that it values more, it will lose that too." W.Somerset Maugham
Précédent
Répondre
Fil
Voir

Click here to load this message in the networking platform