@Test public void testWeiXin(){ System.out.println(task()); } private boolean task(){ try { int i = 10 / 0; System.out.println("i value is" + i); return true; }catch (Exception e){ System.out.println("throws exception" + e); return catchMethod(); }finally { System.out.println("finally"); return finalMethod(); } } private boolean catchMethod(){ System.out.println("execute catchMethod"); return false; } private boolean finalMethod(){ System.out.println("execute finalMethod"); return false; }
执行结果是:
throws exceptionjava.lang.ArithmeticException: / by zeroexecute catchMethodfinallyexecute finalMethodfalse
要点:
1.catch中即使有return存在也会进入到finally中,并且返回结果为finally的返回值。
2.执行顺序是在抛出异常时立马进入catch函数块中,如果有return则先记录返回值,然后进入finally函数块中,如果也有return,则返回值为finally里的返回值,如果没有则为catch函数块里的返回值。
原标题:深入了解try catch
关键词: