java : how to handle the design when template methods throw exception when overrided method not throw

Posted by jiafu on Stack Overflow See other posts from Stack Overflow or by jiafu
Published on 2012-07-01T03:00:40Z Indexed on 2012/07/01 3:15 UTC
Read the original article Hit count: 210

Filed under:
|

when coding. try to solve the puzzle:

how to design the class/methods when InputStreamDigestComputor throw IOException?

It seems we can't use this degisn structure due to the template method throw exception but overrided method not throw it. but if change the overrided method to throw it, will cause other subclass both throw it. So can any good suggestion for this case?

abstract class DigestComputor{


    String compute(DigestAlgorithm algorithm){
        MessageDigest instance;
        try {
            instance = MessageDigest.getInstance(algorithm.toString());
            updateMessageDigest(instance);

            return hex(instance.digest());
        } catch (NoSuchAlgorithmException e) {
            LOG.error(e.getMessage(), e);
            throw new UnsupportedOperationException(e.getMessage(), e);
        }
    }

    abstract void updateMessageDigest(MessageDigest instance);

}

class ByteBufferDigestComputor extends DigestComputor{

    private final ByteBuffer byteBuffer;

    public ByteBufferDigestComputor(ByteBuffer byteBuffer) {
        super();
        this.byteBuffer = byteBuffer;
    }

    @Override
    void updateMessageDigest(MessageDigest instance) {
        instance.update(byteBuffer);

    }

}

class InputStreamDigestComputor extends DigestComputor{


               // this place has error. due to exception. if I change the overrided method to throw it. evey caller will handle the exception. but 
    @Override
    void updateMessageDigest(MessageDigest instance) {
        throw new IOException();

    }

}

© Stack Overflow or respective owner

Related posts about java

Related posts about design