try{}catch{}相关问题

2018-06-03  本文已影响0人  Tuen

try{}catch{}相关问题

1 向上抛出exception与不抛出exception的区别

public class Test1 {
    public static void main(String[]args){
        System.out.println(test1());
    }
    public static int test1(){
        try{
            int a=1/0;
        }catch(Exception e){
            throw e;
        }
        return 1;
    }
}

这样会打出exception

public class Test1 {
    public static void main(String[]args){
        System.out.println(test1());
    }
    public static int test1(){
        try{
            int a=1/0;
        }catch(Exception e){
            //throw e;
        }
        return 1;
    }
}

这样会打印1
由此可以看出,向上抛出异常的时候,上方调用函数是没办法得到返回值的。


2 try{}finally{}语句

try{}代码块后可以只接catch,也可以只接finally,但是必须至少要接一个

public class Test1 {
   private static ArrayList<String> arrayList=new ArrayList<>();
   public static void main(String[]args){
       System.out.println(test1());
   }
   public static int test1(){
       try{
           int a=1/0;
       }finally{
           arrayList.add("haha");
           arrayList.add("sdsa");
       }
       return 1;
   }
}

finally语句会执行,但是还是会向上抛出异常,最终会打印exception
因此try{}finally{}语句相当于

try{
    
}catch(Exception e){
    throw e;
}finally{
    
}

上一篇 下一篇

猜你喜欢

热点阅读