try catch嵌套执行顺序测试

分享一段测试try catch 执行顺序和那些代码后续执行,那么不执行的代码:

 @Test
    public void testTryCatch(){
        try {
            System.out.println(" 外层 try !" );
            //Integer.parseInt(null);
            try {
                System.out.println(" 外层 try的 内层 try " );
                Integer.parseInt(null);
            }
            catch (Exception ex2) {
                Integer.parseInt(null);
                System.out.println(" 外层 try的 内层 catch " );
            }
            finally {
                Integer.parseInt(null);
                System.out.println(" 外层 try的 内层 finally");
            }
            System.out.println("外层 try 异常之后执行!");
            Integer.parseInt(null);
        }
        catch (Exception ex) {
            try {
                System.out.println(" 内层 try " );
                Integer.parseInt(null);
            }
            catch (Exception ex2) {
                System.out.println(" 内层 catch " );
            }
            finally {
                System.out.println(" 内层 finally");
            }
            System.out.println("外层 catch " );
        }
        finally {
            System.out.println("外层 finally!");
        }
    }

通过注释 Integer.parseInt(null); 完成自己想要跑异常的点,完后看后续处理的顺序。

总结:抛出异常的点,后续代码不执行,然后找最近的catch,执行catch和finally,然后再往外层执行。

但是如果catch内部再次出现异常,会往外层抛,直到找到最近的catch。所以在使用嵌套trycatch的时候需要注意的地方就是,哪里会抛出异常,异常的顺序,那些后续可能不会执行。

再分享一段spring的代码

if (this.registrar.hasTasks() && this.registrar.getScheduler() == null) {
    Assert.state(this.beanFactory != null, "BeanFactory must be set to find scheduler by type");
    try {
        // Search for TaskScheduler bean...
        this.registrar.setTaskScheduler(this.beanFactory.getBean(TaskScheduler.class));
    }
    catch (NoSuchBeanDefinitionException ex) {
        logger.debug("Could not find default TaskScheduler bean", ex);
        // Search for ScheduledExecutorService bean next...
        try {
            this.registrar.setScheduler(this.beanFactory.getBean(ScheduledExecutorService.class));
        }
        catch (NoSuchBeanDefinitionException ex2) {
            logger.debug("Could not find default ScheduledExecutorService bean", ex);
            // Giving up -> falling back to default scheduler within the registrar...
        }
    }
}

最后说一下个人的观点,尽量避免使用嵌套异常处理工作。除非逻辑简单,有一定的可读性,不然会极大的影响可读性,另外就是避免一些后续处理逻辑异常。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章