Discuss / Java / 在上游捕获不到下游方法的异常

在上游捕获不到下游方法的异常

Topic source
es.submit(new ProductEvent(observer, p, Event.PRICECHANGED));

try { 
        if (e.equals(Event.ONPUBLISHED)) {
            observer.onPublished(product);
        } else {
            observer.onPriceChanged(product); //该方法内部抛出一个 RuntimeException
        }
} catch (RuntimeException e) {  
        throw new RuntimeException();  //这将无法捕获到异常
}
[Admin Log] on product price changed: Product [name=name, price=456.1]
[Customer Log] on product price changed: Product [name=name, price=456.1]

捕获异常应该精准的作用在异常的方法上

if (e.equals(Event.ONPUBLISHED)) {
    observer.onPublished(product);
} else {
    try {
        observer.onPriceChanged(product);
    } catch (Exception e) {
        e.printStackTrace();
        //TODO: handle exception
    }
}
[Admin Log] on product price changed: Product [name=name, price=456.1]
[Customer Log] on product price changed: Product [name=name, price=456.1]
java.lang.RuntimeException
        at com.learnjava.inform.AdminObserver.onPriceChanged(AdminObserver.java:13)
        at com.learnjava.ProductEvent.run(ProductEvent.java:25)
        at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
        at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
        at java.base/java.lang.Thread.run(Thread.java:832)

  • 1

Reply