gpt4 book ai didi

java - Java中的巨大异常处理 block

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:16:39 24 4
gpt4 key购买 nike

目前我使用的库可能会抛出很多不同的异常(每个方法调用 8-10 个)并且其中大部分必须被处理,更糟糕的是每个方法(在任何时候)都可能抛出 AuthenticationExpiredException ,我必须重新尝试进行身份验证。例如:

try {
xStream = xSet.createXStream(id, binding, mimeType); //Method call
} catch (AuthenticationExpiredException authenticationExpiredException) {
try {
this.authenticate(); // re-authenticate
xStream = xSet.createXStream(id, binding, mimeType); //Method call again
} catch (XAMException xamException) {
throw new ConnectorException(
"Error occurred during creating new Blob after attempting to re-authenticate",
xamException);
}
} catch (XSystemCorruptException xSystemCorruptException) {
this.entities.clear();
this.closeConnection();

throw new ConnectorException("XSystem was corrupt and connection was closed",
xSystemCorruptException);
} catch (XSetCorruptException xSetCorruptException) {
this.closeEntity(entity);

throw new ConnectorException("XSet for entity: " + entity.getXuid()
+ " was currupt and removed", xSetCorruptException);
} catch (XAMException xamException) {
throw new ConnectorException(
"Error occurred during creating new Blob.", xamException);
}

这是异常处理的最小示例之一。这里的主要问题是,有什么方法可以减少处理异常的代码量,并使逻​​辑更清晰?

更新

感谢您的反馈。我决定通过包装每个方法并分别处理它们来为这个库创建单独的包装器。为了支持不同的处理方法,我为包装器创建了接口(interface),然后使用我的自定义包装器实现它,如下所示:

public interface XAMLibraryWrapper{
// Methods
}

/**
* Will attempt to recover before throwing RuntimeException
*/
public class RecoveringXAMLibraryWrapper implements XAMLibraryWrapper{
// Implementation
}

最佳答案

如果有一个一致的方法来处理这些方法(即你总是以相同的方式包装它们并重新抛出一个RuntimeException,那么一个自定义包装器库< em>可能是合适的方法。当有 2-3 种不同的方法来处理它们时,这仍然有效(通过为单个包装方法/类提供 2-3 包装方法(或什至类))。

或者,如果两个或多个异常类型具有完全相同的处理代码,那么您可以尝试寻找 Java 7 to get multi-catch .

关于java - Java中的巨大异常处理 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6982612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com