美文网首页
try{}catch{}相关问题

try{}catch{}相关问题

作者: Tuen | 来源:发表于2018-06-03 17:20 被阅读0次

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
由此可以看出,向上抛出异常的时候,上方调用函数是没办法得到返回值的。

  • 实际上,在throw e;运行完之后,test1()函数就跳出了,不会继续运行return 1;
  • 如果没有throw e;异常会被吃掉,继续向下运行,返回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{
    
}

相关文章

网友评论

      本文标题:try{}catch{}相关问题

      本文链接:https://www.haomeiwen.com/subject/hpnjsftx.html