1 try { 2 //do 3 } catch (Exception e) { 4 //捕获异常 5 } finally { 6 //不管如何总会执行 7 }
在有return的情况下该如何执行
1 public static void main(String[] args) { 2 // TODO Auto-generated method stub 3 System.out.println(test(1)); 4 } 5 public static int test(int i) { 6 try { 7 i++; 8 System.out.println("try-----"+i); 9 return i; 10 } catch (Exception e) { 11 i++; 12 System.out.println("catch----"+i); 13 return i; 14 }finally { 15 i=10; 16 System.out.println("finally---"+i); 17 } 18 } 19 /* 20 结果如下: 21 try-----2 22 finally---10 23 2 24 */
try语句块抛出错误时:
public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(test(1)); } public static int test(int i) { try { i++; System.out.println("try-----"+i); int a = i/0; return i; } catch (Exception e) { i++; System.out.println(e.getMessage()); System.out.println("catch----"+i); return i; }finally { i=10; System.out.println("finally---"+i); } } /*结果如下: try-----2 / by zero catch----3 finally---10 3 */