What is a suppressed exception?

后端 未结 8 1804
借酒劲吻你
借酒劲吻你 2020-11-28 04:51

A comment (by user soc) on an answer to a question about tail call optimisation mentioned that Java 7 has a new feature called \"suppressed exceptions\", because of \"the ad

8条回答
  •  感动是毒
    2020-11-28 05:15

    Concedering the code below:

    public class MultipleExceptionsExample {
    
       static class IOManip implements Closeable{
           @Override
           public void close() {
               throw new RuntimeException("from IOManip.close");
           }
       }
    
       public static void main(String[] args) {
           try(IOManip ioManip = new IOManip()){
               throw new RuntimeException("from try!");
           }catch(Exception e){
               throw new RuntimeException("from catch!");
           }finally{
               throw new RuntimeException("from finally!");
           }
       }
    }
    

    With all lines you will get: java.lang.RuntimeException: from finally!

    Removing finally block you will get: java.lang.RuntimeException: from catch!

    Removing catch block you will get:

    Exception in thread "main" java.lang.RuntimeException: from try!
        Suppressed: java.lang.RuntimeException: from IOManip.close
    

提交回复
热议问题