H.Wat
H.Wat

Reputation: 1

Appropriate Exception when instanceof fails

What is appropriate exception when instanceof fail. Something like this:

if (user instanceof CustomerModel)
    {
            some logic...
    }
    else
    {
        throw new ClassCastException("Current user is not of type Customer");
    }
}

i was going with ClassCastException but i am not 100% sure that it is a good one in this situation.

Upvotes: 0

Views: 1062

Answers (2)

vmrvictor
vmrvictor

Reputation: 723

If this is given as a parameter I would use:

IllegalArgumentException:

Thrown to indicate that a method has been passed an illegal or inappropriate argument

If this is defined by the state of the application then:

IllegalStateException

the Java environment or Java application is not in an appropriate state for the requested operation

Otherwise, I suppose your ClassCastException is ok, but as It was said, then you do not need to create it manually but to cast directly.

Upvotes: 1

Mark Jeronimus
Mark Jeronimus

Reputation: 9543

Like Eran said, if you just want an 'industry standard' ClassCastException, just attempt to cast it and don't use instanceof. If you want a custom exception, well, it depends on what you intend. We need more information about what you want in order to give a better example. I'll just give a random example.

For example, if you intend to validate&cast a method parameter or fail with a custom error message, I usually employ this method:

public static <T, S extends T> S requireType(Class<S> type, T actual, String varName) {
    requireNonNull(actual, varName);
    if (!type.isInstance(actual))
        throw new IllegalArgumentException('\'' + varName + "' must be of type " +
                                           type.getName() +": " + actual.getClass());
    //noinspection unchecked // It is just checked
    return (S)actual;
}

Those scary generic parameters are handled automatically, as in for example:

FirmwarePacket castPacket = requireType(FirmwarePacket.class, packet, "packet");

Upvotes: 1

Related Questions