开发者

Java - Handling Errors from concrete classes that implement 1 interface

In our code we have a number of processors that implement the same interface. By using spring and some arguments in our code, we lookup the correct concrete implementation of the IMsgProcessorInbound class to call.

When an exception occurs in any of these concrete implementations, i would like to catch the expception in the below try catch block.

Unforunately, this try catch block is never entered when an exception is thrown in the concrete implementation.

Is there any way I can catch the exceptions in the catch block listed below instead of littering all my concrete implementations with exception handling code?开发者_C百科 Or is there some error handling functionality that spring can provide me?

IMsgProcessorInbound msgProcessor = msgProcessorSelectorInbound.lookupProcessorInbound(args);


    try {
        msgProcessor.processMsg(fixProcessorArgs);
    } catch (Exception e) {
        log.error("Exception is: " + e);
    }

All help with this issue is greatly appreciated.

Thank you Damien


Check this;

  try {
        msgProcessor.processMsg(fixProcessorArgs);
    } catch (Throwable e) {
        log.error("Exception is: " + e);
    }

msgProcessor.processMsg() may not be throwing a type of Exception. The Throwable class is the superclass of all errors and exceptions. So the above should catch both checked and unchecked exceptions.

If you can't still get into the catch block - then the msgProcessor.processMsg() may be swallowing exceptions.


Can't really give a full answer without knowing more about the problem. What Exception subclass is not getting caught by the try/catch block?

In other words, you state the following:

Unforunately, this try catch block is never entered when an exception is thrown in the concrete implementation.

How do you know this, and what Exception is it that isn't being caught? What is the contract that your processMsg method fulfills (the method signature on the interface)? Does it declare which Exceptions it will throw? If so, which ones?

For the Exceptions that are thrown, do you have a stack trace? If so, is it definitely the line msgProcessor.processMsg(fixProcessorArgs); which is throwing the Exception?

It may also be that, for whatever reason, you need to catch Throwable in your catch, rather than Exception. If you look at the inheritance hierarchy for Exception, you should note that it implements Throwable which is in turn implemented by a number of concrete Error classes. At the moment, your code will not catch any Error's thrown in the try/catch block.


If all your implementation classes should have this maybe it is better to declare a throws and handle the exception one level up in the stack trace.

Updated to reflect a comment from Daniel. Declare a throws in the interface and eclipse will highlight with compiler error where you should put the try catch

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜