Click here to Skip to main content
15,910,981 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hey everyone, im trying to change the value of a variable from within a try statement so that it will effect the variable outside of the try, does anyone know how to do this?
Posted

1 solution

The try block (like any other block of statements) may access outer blocks variables. On the other hand if you define a variable inside the try block itself then you cannot change it outside (see, for instance here[^]).
 
Share this answer
 
Comments
Sicppy 6-Feb-12 16:08pm    
I already tried that, but the changes only effect what is inside the try block. for example if I ran this code(just pretend that the syntax is right)


String x = hi;
try {
x = goodbye;
}
System.out.println(x);


The outcome would still be hi
TorstenH. 7-Feb-12 2:06am    
Your code has an init-value that remains if the try/catch is failing. That is OK, but hard to detect when the catch doesn't make a clear announcement(like forcing a popup). It's better to init on "null"/-1 which is a non valid value and easy to figure in further operations.
CPallini 6-Feb-12 17:02pm    
How could you run it if the syntax is wrong (it is in fact wrong). The following (contrived) example:

int x=10;
try
{
x=15;
}
catch(Exception e)
{
}
int p = x;

assigns 15 to p.
I've tested it.
Sicppy 9-Feb-12 14:34pm    
it was just an example, I have it set up the right way in my actual program. It sets a string. assign's it a value from within a try, but it says the variable isn't initialized when i try System.out.println(x);
from outside of the try block
CPallini 9-Feb-12 15:08pm    
Well, then please post the actual code, in order to let me make a test.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900