473,320 Members | 2,000 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Scope confusion -- compilation issue -- please help me understand

When I compile the following code fragment, the compiler errors saying the variable connection is not initialized. As I understand C#, I thought it would be initialized. Please help me and explain what I am missing

Bil

static void Main(string[] args

SqlConnection connection
try // to open the connection to the database

connection=new SqlConnection((string)( System.Configuration.ConfigurationSettings.AppSett ings["SQLConnection"]))
connection.Open()

catch (Exception e

ProcessInitialException(e)
Environment.Exit(0)

if (args.Length!=2

ProcessArguementError(args)
Environment.Exit(0)

string eventType=args[0]
string userEvent=args[1]
SqlCommand command=new SqlCommand("RetrieveNotificationUsers",connection)

Nov 16 '05 #1
12 1448
initialize it to null:

SqlConnection connection = null;

--------------------------------
| Scott C. Reynolds |
| Tales from the SharpSide |
| http://www.scottcreynolds.com |
--------------------------------
Bill wrote:
When I compile the following code fragment, the compiler errors saying the variable connection is not initialized. As I understand C#, I thought it would be initialized. Please help me and explain what I am missing.

Bill

static void Main(string[] args)
{
SqlConnection connection;
try // to open the connection to the database.
{
connection=new SqlConnection((string)( System.Configuration.ConfigurationSettings.AppSett ings["SQLConnection"]));
connection.Open();
}
catch (Exception e)
{
ProcessInitialException(e);
Environment.Exit(0);
}
if (args.Length!=2 )
{
ProcessArguementError(args);
Environment.Exit(0);
}
string eventType=args[0];
string userEvent=args[1];
SqlCommand command=new SqlCommand("RetrieveNotificationUsers",connection) ;

Nov 16 '05 #2
The problem is that the compiler doesn't know that Environment.Exit never
returns. So if the constructor for SqlConnection threw an exception (leaving
connection uninitialised), the compiler would consider the use of connection
in the last line a potential problem. You and I know better of course.

As far as I know the best way to avoid this is to stick a 'throw new
Exception()' after the first Environment.Exit, but if somebody knows of an
attribute or similar that could be employed in this sort of situation I'd be
interested.

Stu
"Bill" <an*******@discussions.microsoft.com> wrote in message
news:6B**********************************@microsof t.com...
When I compile the following code fragment, the compiler errors saying the variable connection is not initialized. As I understand C#, I thought it
would be initialized. Please help me and explain what I am missing.
Bill

static void Main(string[] args)
{
SqlConnection connection;
try // to open the connection to the database.
{
connection=new SqlConnection((string)( System.Configuration.ConfigurationSettings.AppSett ings["SQLConnection"])); connection.Open();
}
catch (Exception e)
{
ProcessInitialException(e);
Environment.Exit(0);
}
if (args.Length!=2 )
{
ProcessArguementError(args);
Environment.Exit(0);
}
string eventType=args[0];
string userEvent=args[1];
SqlCommand command=new SqlCommand("RetrieveNotificationUsers",connection) ;

Nov 16 '05 #3
Bill <an*******@discussions.microsoft.com> wrote:
When I compile the following code fragment, the compiler errors
saying the variable connection is not initialized. As I understand
C#, I thought it would be initialized. Please help me and explain
what I am missing.


The problem is that the compiler doesn't know that Environment.Exit(0)
is going to quit the runtime, so it thinks that it's possible for you
to throw and catch an exception, and then move on to the later bit of
code - which would involve reading the connection variable which
wouldn't have been initialised.

You could stick a return statement after Environment.Exit(0); which
wouldn't do any harm but would clear the error - or set the connection
to null to start with.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #4
Belay my last.

Really, unless there is some reason that getting the SQLConnection key
from the appsettings would fail, I would take that line out of the
try//catch altogether. So you would just have

SqlConnection connection = new
SqlConnection(System.Configuration.ConfigurationSe ttings.AppSettings["SqlConnection"]);
and then try to open the connection.

You shouldn't need to cast that to (string) since
AppSettings["blahblah"] should be returning a string anyway.

In order for it to compile, you need connection to be initialized to
*something* to reference it later, and since the code in try{} may not
run, the compiler does not recognize that it would work, and throws the
error.

Keep your trys as lean as possible, as try{}catch{} runs pretty slow.

--------------------------------
| Scott C. Reynolds |
| Tales from the SharpSide |
| http://www.scottcreynolds.com |
--------------------------------
Bill wrote:
When I compile the following code fragment, the compiler errors saying the variable connection is not initialized. As I understand C#, I thought it would be initialized. Please help me and explain what I am missing.

Bill

static void Main(string[] args)
{
SqlConnection connection;
try // to open the connection to the database.
{
connection=new SqlConnection((string)( System.Configuration.ConfigurationSettings.AppSett ings["SQLConnection"]));
connection.Open();
}
catch (Exception e)
{
ProcessInitialException(e);
Environment.Exit(0);
}
if (args.Length!=2 )
{
ProcessArguementError(args);
Environment.Exit(0);
}
string eventType=args[0];
string userEvent=args[1];
SqlCommand command=new SqlCommand("RetrieveNotificationUsers",connection) ;

Nov 16 '05 #5


----- Scott C. Reynolds wrote: ----
Keep your trys as lean as possible, as try{}catch{} runs pretty slow


no, there's only performance penalty if an exception was actually thrown. I've never read any standard saying to keep your try block lean.
Nov 16 '05 #6
You know, you are right. I have never given it that much thought. You
should avoid exception handling just for the sake of exception handling
(such as catching something that could have easily been handled with an
if()), but there is no reason not to put whatever you want in the try
block. It has just always been my practice to try{thebareminimum();},
but it is by no means required.

So, it is back to initialize connection to null before the try block, or
pull the creating the instance out of the try anyway unless you feel
like it might fail, because one way or the other the compiler doesn't
know you are exiting the application and will nag you if you try to use
a potentially uninitialzed object.

--------------------------------
| Scott C. Reynolds |
| Tales from the SharpSide |
| http://www.scottcreynolds.com |
--------------------------------
Daniel Jin wrote:

----- Scott C. Reynolds wrote: -----
> Keep your trys as lean as possible, as try{}catch{} runs pretty slow.


no, there's only performance penalty if an exception was actually thrown. I've never read any standard saying to keep your try block lean.

Nov 16 '05 #7

"Daniel Jin" <an*******@discussions.microsoft.com> wrote in message
news:44**********************************@microsof t.com...


----- Scott C. Reynolds wrote: -----
> Keep your trys as lean as possible, as try{}catch{} runs pretty
slow.
no, there's only performance penalty if an exception was actually

thrown. I've never read any standard saying to keep your try block lean.

This is not true.

Setting up the try-block do indeed cost several 100'000 cycles. For typical
applications this is neglectable. For high-performing tight heavy loops -
exception handling (try-blocks inside the loop) do takes it toll and really
hurts performance.

But in this context, using a sql connection, I would never even consider
getting rid of the try-block. Not for readablility and certainly not for
performance reasons.

Best Regards
- Michael S
Nov 16 '05 #8
Hi, Michael

How did you get the figures for try/catch? Any pointers to benchmarks or
test samples?
Setting up the try-block do indeed cost several 100'000 cycles. For typical applications this is neglectable. For high-performing tight heavy loops -
exception handling (try-blocks inside the loop) do takes it toll and really hurts performance.


Nov 16 '05 #9
Michael S <a@b.c> wrote:
This is not true.

Setting up the try-block do indeed cost several 100'000 cycles.


While I agree it's not absolutely free, I don't think it takes *that*
much time. For instance:

using System;

public class Test
{
static int x;
static int y=0;

const int Iterations = 100000000;

static void Main()
{
y=1;
DateTime start=DateTime.Now;
for (int i=0; i < Iterations; i++)
{
IncX();
}
DateTime end=DateTime.Now;

Console.WriteLine ("Time for {0} iterations: {1}",
Iterations, end-start);
}

static void IncX()
{
try
{
if (y==0)
{
throw new Exception ("Whoops");
}
x++;
}
catch (Exception e)
{
throw new ApplicationException("Yikes "+e.Message);
}
}
}

On my P4/3GHz laptop, the results are that it takes about a second for
the 100,000,000 iterations. If each iteration were taking even one
hundred thousand cycles, that would suggest that my laptop were capable
of executing 10^13 cycles per second. I don't believe that's the case.

Note that if I replace IncX with:

[MethodImpl(MethodImplOptions.NoInlining)]
static void IncX()
{
x++;
}

the test takes between 0.4 and 0.8 seconds. Say it takes about half the
time of the version which includes try/catch. That suggests that

method invocation + try/catch + increment takes twice as long as
method invocation + increment

In other words, the cost of setting up a try/catch is the same as a
method invocation and an increment. Do you really think that *that*
takes several hundred thousand cycles?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #10
Thanks Jon for dropping some stats and sample.

On my 1GHz your test shows that try/catch in static method body increases
runtime on average by 0.75 sec for 100M iterations. Approx. 30% of total
execution time (2.3). Considering that clean x++ in for loop gives me around
0.65, I would say that overhead is not significantly more than general cost
of for body, which is 12 IL ops like stloc/ldloc, ldsfld/stsfld, blt, ldc
and couple of add.

I would conclude, that general cost of setting up try/catch block is
negligible for nearly all .Net applications. It is worth to consider related
overhead only in computation intensive cases and even then it is
questionable if result is worth the effort.

Rgds
Alex
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Michael S <a@b.c> wrote:
This is not true.

Setting up the try-block do indeed cost several 100'000 cycles.


While I agree it's not absolutely free, I don't think it takes *that*
much time. For instance:

using System;

public class Test
{
static int x;
static int y=0;

const int Iterations = 100000000;

static void Main()
{
y=1;
DateTime start=DateTime.Now;
for (int i=0; i < Iterations; i++)
{
IncX();
}
DateTime end=DateTime.Now;

Console.WriteLine ("Time for {0} iterations: {1}",
Iterations, end-start);
}

static void IncX()
{
try
{
if (y==0)
{
throw new Exception ("Whoops");
}
x++;
}
catch (Exception e)
{
throw new ApplicationException("Yikes "+e.Message);
}
}
}

On my P4/3GHz laptop, the results are that it takes about a second for
the 100,000,000 iterations. If each iteration were taking even one
hundred thousand cycles, that would suggest that my laptop were capable
of executing 10^13 cycles per second. I don't believe that's the case.

Note that if I replace IncX with:

[MethodImpl(MethodImplOptions.NoInlining)]
static void IncX()
{
x++;
}

the test takes between 0.4 and 0.8 seconds. Say it takes about half the
time of the version which includes try/catch. That suggests that

method invocation + try/catch + increment takes twice as long as
method invocation + increment

In other words, the cost of setting up a try/catch is the same as a
method invocation and an increment. Do you really think that *that*
takes several hundred thousand cycles?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #11
Hi Jon.

About my *that* long time it's something I remembered from a discussion on
Microsoft C++ and Borland Delphi compilers. I have no links, sorry.

Regarding your test; Was it compiled in debug or release mode? Also, for
such a small scale test, using DateTime.Now to time performance is way to
crude.

The point is still made clear: Setting up a try-block take *some* time. For
tight loops there is a noticable penalty. However, getting rid of try blocks
for performance considerations is just plain wrong. Agreed?

Best Regards
- Michael S

ps.
On a more funny side: A friend of mine applied for work at a game-shop. As
he being brainwashed by managed code (mainly in Java), at the job interview,
he started talking about the importance of exception handling, assertions,
interfaces and factories for making robust quality code. Their response
was: - We do computer games. Most our code is in asm!

... He didn't get the job... =)
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Michael S <a@b.c> wrote:
This is not true.

Setting up the try-block do indeed cost several 100'000 cycles.


While I agree it's not absolutely free, I don't think it takes *that*
much time. For instance:

using System;

public class Test
{
static int x;
static int y=0;

const int Iterations = 100000000;

static void Main()
{
y=1;
DateTime start=DateTime.Now;
for (int i=0; i < Iterations; i++)
{
IncX();
}
DateTime end=DateTime.Now;

Console.WriteLine ("Time for {0} iterations: {1}",
Iterations, end-start);
}

static void IncX()
{
try
{
if (y==0)
{
throw new Exception ("Whoops");
}
x++;
}
catch (Exception e)
{
throw new ApplicationException("Yikes "+e.Message);
}
}
}

On my P4/3GHz laptop, the results are that it takes about a second for
the 100,000,000 iterations. If each iteration were taking even one
hundred thousand cycles, that would suggest that my laptop were capable
of executing 10^13 cycles per second. I don't believe that's the case.

Note that if I replace IncX with:

[MethodImpl(MethodImplOptions.NoInlining)]
static void IncX()
{
x++;
}

the test takes between 0.4 and 0.8 seconds. Say it takes about half the
time of the version which includes try/catch. That suggests that

method invocation + try/catch + increment takes twice as long as
method invocation + increment

In other words, the cost of setting up a try/catch is the same as a
method invocation and an increment. Do you really think that *that*
takes several hundred thousand cycles?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #12
Michael S <a@b.c> wrote:
About my *that* long time it's something I remembered from a discussion on
Microsoft C++ and Borland Delphi compilers. I have no links, sorry.

Regarding your test; Was it compiled in debug or release mode?
Release.
Also, for
such a small scale test, using DateTime.Now to time performance is way to
crude.
It's not so bad on a second or so. Much less than that and it's too
crude, I'll admit. It doesn't matter here though - these were only
rough timings, and it was obvious that it was taking "about a second".
If I'd been interested in very accurate timings, I'd have upped the
number of iterations.
The point is still made clear: Setting up a try-block take *some* time. For
tight loops there is a noticable penalty. However, getting rid of try blocks
for performance considerations is just plain wrong. Agreed?
Agreed. If it were really taking hundreds of thousands of cycles,
however, it *would* be a valid thing to try to optimise in many
situations. As it is, only a very tight loop would benefit
significantly from removing it.
ps.
On a more funny side: A friend of mine applied for work at a game-shop. As
he being brainwashed by managed code (mainly in Java), at the job interview,
he started talking about the importance of exception handling, assertions,
interfaces and factories for making robust quality code. Their response
was: - We do computer games. Most our code is in asm!

.. He didn't get the job... =)


Interesting, as most games are (I believe) written in C or C++ these
days...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: pembed2003 | last post by:
Hi all, I am reading the book "C++ How to Program" and in the chapter where it discuss scope rule, it says there are four scopes for a variable: function scope file scope block scope...
5
by: Ondrej Spanel | last post by:
I though that inline functions should be always visible only in the compilation unit where they are defined - meaning if compiler cannot inline them, they should be handled as if declared static....
4
by: Gery D. Dorazio | last post by:
Gurus, If a static variable is defined in a class what is the scope of the variable resolved to for it to remain 'static'? For instance, lets say I create a class library assembly that is...
2
by: Geoff | last post by:
Hi. I'm very confused about what gets compiled to what, and what gets cached where, and what gets persisted, and what is shared between users. Could someone possibly check my understanding of the...
165
by: Dieter | last post by:
Hi. In the snippet of code below, I'm trying to understand why when the struct dirent ** namelist is declared with "file" scope, I don't have a problem freeing the allocated memory. But...
6
by: shaun | last post by:
If I put (define) const variables at the top of a .cpp file but do not declare them in the .h file, are they only visible within that .cpp file? e.g. const int a={1,2,3,4}; in a cpp file...
39
by: Martin Jørgensen | last post by:
Hi, I'm relatively new with C-programming and even though I've read about pointers and arrays many times, it's a topic that is a little confusing to me - at least at this moment: ---- 1)...
7
by: WXS | last post by:
Vote for this idea if you like it here: http://lab.msdn.microsoft.com/productfeedback/viewfeedback.aspx?feedbackid=5fee280d-085e-4fe2-af35-254fbbe96ee9...
35
by: mwelsh1118 | last post by:
Why doesn't C# allow incremental compilation like Java? Specifically, in Java I can compile single .java files in isolation. The resulting individual .class files can be grouped into .jar files....
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.