try {} assignment

Hi,
How come when i do an assignment inside a try{} block and afterwards try to use the assigned variable it tells me I am using it without assigning?
Take this for example:
----------------------------
int a;
try{a=some_function();}
catch(Exception e)
{<some code>}
MessageBox.Show(a.ToString ());
-----------------------------------
I get the error message when compiling: Use of unassigned local variable 'a' (in the MessageBox line)

If i were to insert the line 'a=5' before the 'try' it would compile and work fine.
Am i missing something here?
deniX23Asked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
razoConnect With a Mentor Commented:
because the program takes into account the possibilty that the code would enter the catck block instead of the try block and in that instance the int a is not assigned to any value
0
 
nouloukCommented:
Hi denix23,

With int, you have to assigned a value when you declare the variable:
int a=0;
particulary if you use try {}.

Another way possible:
try{
int a;
a=some_function();
MessageBox.Show(a.ToString ());              ----Or myfunction() to do what I want.
}
catch(Exception e)
{<some code>}

Hope this will help you.
0
All Courses

From novice to tech pro — start learning today.