If we write return statement in try, catch and finally block, which one will execute when and why ?
Respuestas de entrevistas
Anónimo
8 may 2012
The return written in finally will take precedence over others.
Anónimo
29 jun 2015
Finally block will definitely execute, because it always gets executed and very important code is to be put in finally block like closing of file, return statement etc.
Anónimo
19 oct 2016
public class TryCatch {
public static int getReturn() {
try {
return 1;
}
catch(Exception e) {
return 2;
}
finally {
return 3;
}
}
public static void main(String[] args) {
System.out.println(getReturn());
}
}
3 will be returned.
Anónimo
1 oct 2012
public class trycatch {
public static void main(String[] args) {
trycatch tc = new trycatch();
System.out.println(tc.tryCatch());
}
public int tryCatch(){
try{
//return 1;
System.out.println("try");
throw new Exception();
}catch(Exception e){
System.out.println("catch");
return 2;
}finally{
System.out.println("finally");
return 3;
}
}
}
Output:
try
catch
finally
3