Java中的巨大异常处理块

YoK*_*YoK 9 java exception-handling

目前我正在使用库,它可以抛出很多不同的异常(每个方法调用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);
    }
Run Code Online (Sandbox Code Playgroud)

这是异常处理的最小例子之一.这里的主要问题是,有没有办法减少处理异常的代码量,并使逻​​辑更清晰?

UPDATE

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

public interface XAMLibraryWrapper{
    // Methods
}

/**
 * Will attempt to recover before throwing RuntimeException
 */
public class RecoveringXAMLibraryWrapper implements XAMLibraryWrapper{
    // Implementation
}
Run Code Online (Sandbox Code Playgroud)

Joa*_*uer 6

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

或者,如果两个或多个异常类型具有完全相同的处理代码,那么您可以尝试查找Java 7 以获得多次捕获.