Pergunta de entrevista da empresa Model N

If we write return statement in try, catch and finally block, which one will execute when and why ?

Respostas da entrevista

Sigiloso

8 de mai. de 2012

The return written in finally will take precedence over others.

Sigiloso

29 de jun. de 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.

Sigiloso

19 de out. de 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.

Sigiloso

1 de out. de 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