Java笔试面试总结—try、catch、finally语句中有return 的各类情况
前言 之前在刷笔试题和面试的时候经常会遇到或者被问到 try-catch-finally 语法块的执行顺序等问题,今天就抽空整理了一下这个知识点,然后记录下来。 正文 本篇文章主要是通过举例的方式来阐述各种情况,我这里根据 try-catch-finally 语法块分为两种大情况讨论:try-catch 语法块和 try-catch-finally 语句块,然后再在每种情况里再去具体讨论。 一、try-catch 语句块 我们可以看看下面程序: public static void main(String[] args) { System.out.println(handleException0()); } /** * try,catch都有return * @return */ private static String handleException0() { try{ System.out.println("try开始"); String s = null; int length = s.charAt(0); System.out.println("try结束"); return "try块的返回值"; }catch (Exception e){ System.out.println("捕获到了异常"); return "catch的返回值"; } } 执行结果 :