java-try...catch...finally

try...catch...finally
由两段代码展开下面要讨论的话题

public class Try {

        public static String output="";
        public static void foo(int i){
            try{
                if(i==1){
                    throw new Exception();
                }
            }catch(Exception e){
                output+="2";
                return;

            }finally{
                output+="3";

            }
            output+="4";
        }
    public static void main(String[] args) {
        foo(0);
        foo(1);
        System.out.println(output);
        }
    }
运行结果:3423
public class Try {

        public static String output="";
        public static void foo(int i){
            try{
                if(i==1){
                    throw new Exception();
                }
            }catch(Exception e){
                output+="2";                
            }finally{
                output+="3";

            }
            output+="4";
        }
    public static void main(String[] args) {
        foo(0);
        foo(1);
        System.out.println(output);
        }
    }
运行结果:34234

try..catch...finally与直接throw的区别:try是对抛出的异常进行处理,不论是隐式的的异常还是用throw直接抛出的异常,处理完成之后,根据某些规则决定程序是否继续执行。throw是将异常抛给与他对应的try处理,若么有对应的try,则执行完fianlly后,程序一定终止执行

public class Try {    
    public static void main(String[] args) {    
            try{
                int i=100/0;
                System.out.println(i);
            }catch(Exception e){
                System.out.print(1);
                throw new RuntimeException();

            }finally{
                System.out.print(2);                
            }
            System.out.print(3);
        }
    }

运行结果:3423
public class TestDemo {    
    public static int add(int a,int b){
        try{
            return a+b;
        }catch(Exception e){
            System.out.println("catch语句快");        
        }finally{
            System.out.println("finally语句快");        
        }
        return b;
    }
    public static void main(String[] args) {    
        TestDemo t=new TestDemo();
        System.out.println("和是"+t.add(9,34));        
    }
}
运行结果:
finally语句快
和是43

总结一下:

  1. 只有try中发生异常,catch中的语句才执行
  2. 不论try中是否发生异常,finally 中的语句都执行
  3. 若 try...catch...finally中有return,则try...catch...finally后的语句不会执行
  4. 即使try和catch中有return,finally仍会被执行
  5. 若try或catch中有return,finally中没有return,则先把返回值保存起来,不管finally中代码如何,返回值不会改变,等待finally中代码执行完毕,再将返回值返回即可。
  6. 若finally中有return,则返回值不是try或catch中保存的返回值,而是finally中的返回值,即使finally中的return会覆盖try或catch中的return,try或catch中的return不会执行
  7. 如果有多个catch用于捕捉不同的异常,记住,一旦捕捉到一种类型的异常,后面层级更高的异常就不会执行了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值