Why do Java people frequently consume exceptions silently?

前端 未结 28 1701
傲寒
傲寒 2020-11-29 17:50

I never did any serious Java coding before, but I learned the syntax, libraries, and concepts based on my existing skills (Delphi & C#). One thing I hardly understand i

28条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 18:18

    Because they haven't learned this trick yet:

    class ExceptionUtils {
        public static RuntimeException cloak(Throwable t) {
            return ExceptionUtils.castAndRethrow(t);
        }
    
        @SuppressWarnings("unchecked")
        private static  X castAndRethrow(Throwable t) throws X {
            throw (X) t;
        }
    }
    
    class Main {
        public static void main(String[] args) { // Note no "throws" declaration
            try {
                // Do stuff that can throw IOException
            } catch (IOException ex) {
                // Pretend to throw RuntimeException, but really rethrowing the IOException
                throw ExceptionUtils.cloak(ex);
            }
        }
    }
    

提交回复
热议问题