kevinarpe
kevinarpe

Reputation: 21309

Casting Exceptions Using Generic Type Parameters: Right way to do it?

Here is my sample class with embedded comments/questions. Can you please advise the best way to handle this situation?

public abstract class AbstractThreadWithException<TException extends Exception>
extends Thread {

    private TException _exception;

    public TException getException() {
        return _exception;
    }

    // I don't like this annotation: SuppressWarnings.  Is there a work-around?
    // I noticed Google Guava code works very hard to avoid these annos.
    @SuppressWarnings("unchecked")
    @Override
    public void run() {
        try {
            runWithException();
        }
        // By Java rules (at least what my compiler says):
        // I cannot catch type TException here.
        catch (Exception e) {
            // This cast requires the SuppressWarnings annotation above.
            _exception = (TException) e;
        }
    }

    public abstract void runWithException()
    throws TException;
}

I suppose it would be possible to pass a reference to Class<? extends Exception>, but that seems ugly. Is there a more graceful solution?

Unfortunately, my brain is more hard-wired to C++ thinking than Java thinking, hence the confusion surrounding templates vs. generics. I think this problem is related to type erasure, but I am not 100% sure.

Upvotes: 4

Views: 127

Answers (1)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

You are trying to recover runtime type information, so yes you'll need Class.cast or similar. As it stands your code can throw a ClassCastException at the caller of getException because you are catching and storing all Exceptions.

You may find it better to remove the generics and have the caller use instanceof or similar.

Upvotes: 2

Related Questions