PDA

View Full Version : Try and catch


dollar489
01-18-03, 21:18
Hello guys,
Why can't I return something from a method if I have the code in try and catch, e.g.

public String getURL()
{
try{
some code here
return "yahoo.com";
}
catch{
some code here
}


}//end of method

somehow it complains about the return type, any suggestions on how to make this work.

Paul

tswern
01-18-03, 22:06
Originally posted by dollar489
Hello guys,
Why can't I return something from a method if I have the code in try and catch, e.g.

public String getURL()
{
try{
some code here
return "yahoo.com";
}
catch{
some code here
}


}//end of method

somehow it complains about the return type, any suggestions on how to make this work.

Paul

Try putting the return statement outside the catch block. or, try this:

[QUOTE][SIZE=1]Originally posted by dollar489
Hello guys,
Why can't I return something from a method if I have the code in try and catch, e.g.

public String getURL()
{
String yourvar = null;

try{
some code here

}
catch{
some code here
}finally{

return yourvar;
}

}

dollar489
01-19-03, 08:16
Thanks for the response, but I don't want to return anything if something is wrong. Finally will execute no matter what!!!


dollar

Originally posted by tswern
Try putting the return statement outside the catch block. or, try this:

[QUOTE][SIZE=1]Originally posted by dollar489
Hello guys,
Why can't I return something from a method if I have the code in try and catch, e.g.

public String getURL()
{
String yourvar = null;

try{
some code here

}
catch{
some code here
}finally{

return yourvar;
}

}

Jessé Goncalves
01-22-03, 12:46
My friend,

yol'll cannot have a method with some type instead void, without getting a result back. Your problem is that you need to put the "return" outside the Try/Catch block. Otherwise, the compiler will not be able to return something, and it is a necessity. So, the possible way could be:

public class test {

public java.lang.String testVar;

/** Creates a new instance of teste */
public test() {
}

public static void main(java.lang.String[] args){
test t = new test();
t.pushValue();
}

public void pushValue(){

try{
testVar = "oi";
}catch(java.lang.Exception e){
System.out.println("Wrong teste "+e.getMessage());
}

}

}

So, the variable is inicialized just, and just, when the try is respected. Thus, this could help you??

Bye.