Java interview questions 3:try… Catch… Finally

3 what’s wrong with the following code?

Try {return 0;} catch (Exception, e) {return 1;} finally {return 2;} return 3;

Answer:
last return 3 will cause compile error: Unreachable code.

Analysis:
(1) will execute the finally block regardless of whether there is a return statement in the try block or in the catch block.
(2) return return statement in the finally block will cover the front (the return statement in the catch block, try block), so if there is a return statement in the finally block, the Eclipse compiler will report “finally block does not complete warning normally”.
(3) if the finally block contains a return statement, even if the block in front of the catch rethrows the exception, this method is called the statement will not get catch block rethrows the exception, but will be the return value of the finally block, and no exception.

Experiment 1:

Public class MyTest public static int (func) {{try} {return 0; catch (Exception E) {return 1;} finally {return 2}}; public static void main (String[] args) {int = func (RES); System.out.println (res= + RES);}}

Operation result:

Res=2

Experiment 2:

Public class MyTest public static int (func) {try {int {a = 2 / 0; return 0;} catch (Exception E) {System.out.println ("exception"); (e.printStackTrace); return 1;} finally {return}} 2; public static void main (String[] args) {int res = (func); System.out.println (res= + RES);}}

Operation result:

Capturing exceptions: java.lang.ArithmeticException: / by, zero, at, Test.func (Test.java:6), at, Test.main (Test.java:18), res=2