springboot代码如下,执行sync方法,在sa方法中报错了,为啥就不往下执行了,zmr没有执行?

如何让,无论sa报不报错,zmr都执行?

    public void sync() {
        Sa();
        Zmr();
    }

补充,有没有简洁一点的方案,因为需要并行的方法太多了,总不能每一个都加一个trycatch吧?
在springboot中使用的

public void sync() {
    Sa();
    Zmr();
    abc();
    bcd();
}
阅读 1.6k
2 个回答

使用 try 解决:

public void sync() {
    try {
        Sa();
    } catch (Exception e) {
        e.printStackTrace();
    }
    Zmr();
}

更加彻底一点,加上 finally

public void sync() {
    try {
        Sa();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        Zmr();
    }
}

更简洁一点,不过执行完 finally 之后,后面的代码依然会中断:

public void sync() {
    try {
        Sa();
    } finally {
        Zmr();
    }
}

更新,增加一个工具类

利用一个工具类辅助你的函数运行。

如果你的方法没有任何参数,可以很方便的调用,如果有,那么必须要显式的使用 lambda 调用。

另外在 java 中,对于已知异常必须要显式捕捉,不过正常使用也需要,这不是什么问题。

更加进阶一点的问题是,怎么传递有返回值的方法,利用 jdk8 的 Consumer、Function、Runnable 等特性,自己创造一个 RunTool 来辅助你返回调用函数的返回值,下面的例子中,就可以这样使用 System.out.println(RunCatchUtil.run(test::run4));
public class RunCatchUtil {
    @FunctionalInterface
    public interface RunTool<T> {
        T run();
    }

    public static void run(Runnable runnable) {
        try {
            runnable.run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static <T> T run(RunTool<T> c) {
        try {
            return c.run();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static class Test {
        public void run1() throws RuntimeException {
            System.out.println("run1");
            throw new RuntimeException("run1");
        }

        public void run2(String value) throws RuntimeException {
            System.out.println("run2" + ":" + value);
            throw new RuntimeException("run2");
        }

        public void run3() throws Exception {
            System.out.println("run3");
            throw new Exception("run3");
        }

        public String run4() {
            System.out.println("run4");
            return "run4";
        }
    }

    public static void main(String[] args) {
        Test test = new Test();
        RunCatchUtil.run(test::run1);
        RunCatchUtil.run(() -> {
            test.run2("run2");
        });
        RunCatchUtil.run(() -> {
            try {
                test.run3();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        System.out.println(RunCatchUtil.run(test::run4));
    }
}
public void sync(){
 try{
    sa();
}catch(Exception e){

}
    Zmr();
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题