日期:2014-05-20  浏览次数:20940 次

finally的用法。。。
异常捕获
try{
}catch(){
}finally{
      语句1
}
语句2

老师说finally中的代码,无论异常不异常都会执行。可是语句2也是无论有没有捕获到异常也会顺序执行下来啊,那finally岂不是可以在任何情况下都没必要用?请高人指点~

------解决方案--------------------
语句2可不一定会执行。
比如
try {

} catch (**Exception ex) {

} finally {
return;
}

这时try ...catch块之后的代码肯定不会执行的吧。呵呵。
------解决方案--------------------
finally子句的作用主要是当抛出的异常没有被捕获时用来释放内存,和恢复调用的资源.
就是执行了finally子句以后,程序要回到抛出异常的地方,而不是执行finally后面的语句.
------解决方案--------------------
如果有异常那么会直接执行catch块,语句2就不一定回执行,finally的使用取决你自己,比如:连接数据库,你可以把数据库对象的关闭全部写到finally块中,那么表示有没有异常都会执行数据库的关闭,这样的结构比较安全
------解决方案--------------------
try{
}catch(){
}finally{
语句1
}
语句2
语句2在TRY里面存在异常时候是不会运行的
你可以试下在TRY里面 throw new IllegalAccessException( "自编例外 ");
语句1无论是否存在异常都会执行
try{
System.out.println( "before throw exception ");
throw new IllegalAccessException( "new exception ");
System.out.println( "Behind throw exception ");
}
catch(){
System.out.println( "e.printStackTrace() ");
}
finally{
System.out.println( "run finally ");

}
System.out.println( "out of try ");
------解决方案--------------------
catch (IllegalAccessException e)
晕了 catch里面应该这样写 LZ您试下就知道了 然后在把throw new IllegalAccessException( "new exception ");去掉在运行下就明白 TRY是怎么用的了
------解决方案--------------------
也许catch到exception就在catch块中就return了,但finally能保证这一块在return之前执行,放到trycatchfinanly块外面的就无法执行了
------解决方案--------------------
try {
System.exit(0);
}
catch {}
finally{}
此时finally语句好像也不执行
------解决方案--------------------
退出系统当然不执行了````
------解决方案--------------------
try{
System.out.println( "test1 ");
return;
// Integer.parseInt( "a ");
// System.out.println( "test2 ");
}catch(Exception e){
System.out.println( "test3 ");
}finally{
System.out.println( "test4 ");
}
System.out.println( "test5 ");


test1
test4

------解决方案--------------------
语句2可以被执行是因为你的try...catch语句中间没有写throw语句,如果有throw语句,则程序再执行到这一步的时候会自动跳出,类似于GOTO语句;这时候 语句2 中的语句就不能被执行了,但是finally中的语句却仍然可以被执行,这个就类似于c++中的析构函数。。。