deniX23
asked on
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?
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?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
}
catch(Exception e)
{<some code>}
Hope this will help you.