java基础之try-catch-finally

来源:互联网 发布:樱井知香黑人 编辑:程序博客网 时间:2024/06/04 19:46

try-catch的使用

try-catch能够保证程序的正常运行下去。如果没有try-catch,出现异常会导致程序崩溃。下面是一些关于try-catch的使用细节。

1、首先注意catch中如果不抛出异常。

static void test(){int x = 1;try{x = x / 0;//除以0,报异常System.out.println("try");}catch(Exception e){e.printStackTrace();System.out.println("catch");}finally{++x;System.out.println("finally");}System.out.println("test end");}
结果:
java.lang.ArithmeticException: / by zeroat myTest.TestTry.test(TestTry.java:20)at myTest.TestTry.main(TestTry.java:13)catchfinallytest end
说明:通过输出结果可以看出,程序即使出现异常也会执行到最后。如果在catch中加throw new RuntimeException();则程序跑完finally,便会将异常跑到main函数中。不再执行finally下面的程序。

2、包含return,无异常抛出

static int test(){int x = 1;try{System.out.println("try");return x;}catch(Exception e){System.out.println("catch");return x;}finally{++x;System.out.println("finally");}}
结果:
tryfinally1
说明:finally会在return的中间执行,所谓中间即使,程序跑到try中的return的时候,便是要返回了,但是有finally,所以继续跑finally中的代码,跑完之后,便回到try中的return  x; 虽然finally已经将x加1了,但是程序本应该已经返回的。其实可以理解为,test函数遇到try中的return时候已经准备返回了,返回的值也已经准备好了。就等finally运行完事。所以结果就是1。所以说finally是在return中间返回。

但是如果在finally中加上return的话,这程序跑到finally的return后便直接返回了。因为finally中也有return,并且没有执行的代码了,便会返回2。

3、包含return,并且有异常抛出

如果finally中不含return的话,结果和第一种一样。跑完finally紧跟着抛出异常。
如果finally中包含return的话:
static int test(){int x = 1;try{System.out.println("try");x = x/0;return x;}catch(Exception e){System.out.println("catch");throw new RuntimeException();}finally{++x;System.out.println("finally");return x;}}
结果:
<pre name="code" class="java"><pre name="code" class="html">trycatchfinally2
结果:
try
catch
finally
2
说明:程序准备跑出异常时,发现有finally要执行,并开始执行finally。执行finally的时候发现有return要执行,此时没有应该执行的代码了,程序便直接return了,也不会跑出本应该跑出的异常了。










0 0
原创粉丝点击