Java exception wrapping: bad practice?

From the PHP world, there is only one way to write exception handling I find the exception wrapper in java a little "ugly":

public void exampleOneException(String input) throws MyBusinessException {
    try {
        // do something
    } catch (NumberFormatException e) {
        throw new MyBusinessException("Error...",e);
    }
}

I prefer this style:

public void exampleTwoexception() {
    try {
        // do something
    } catch (MyBusinessException e) {
        log.error("Error...: " + e);
    } catch (NumberFormatException e) {
        log.error("Error...: " + e);
    }
}

Are there any differences or best practices in these approaches to exceptions?

Solution

These are effective methods for two different scenarios

In the first case, the method cannot do any intelligence on the exception, but it must "report" it up In this way, the caller can catch the exception and decide how to handle it (for example, cancel the flow, pop up a message to the user, record it, etc.)

In the second case, you catch the exception and log it, effectively hiding the error from the caller Such processing can be useful if the caller does not really care about the success of the operation

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>