When should NoSuchFieldException be used versus NoSuchElementException?

172 Views Asked by At

Aside from NoSuchFieldException being a checked exception, where NoSuchElementException is not, what are the differences between the two exceptions? When should one be used as opposed to the other?

Specifically, I am working on an OOP representation to encapsulate Valve Server Query A2S_INFO Packets, where some values can be present or not depending on the value for the Extra Data Flag (EDF) (more specifically, the presence of these values can be tested using bit-wise AND with given constants.) The getter methods should provide the value if it is present, and throw an exception if not. This is where the initial question comes from, as I don't know what would be more beneficial to use here.

The code below shows one of the getter methods for a field that can be present or not depending on the value of the EDF:

public long getSteamID(){
    if(containsSteamID){
        return steamID;
    }else{
        //Should NoSuchElementException be used here or NoSuchFieldException?
        throw new NoSuchElementException("There is no steamID in this packet.");
    }
}
1

There are 1 best solutions below

1
On

NoSuchFieldException is for reflection based access, it (quoting the docs) "signals that the [Java] class doesn't have a field of a specified name." The documentation also shows (at least for checked exceptions) from which JDK methods it is thrown. Since you are not using Java reflection, NoSuchFieldException seems inappropriate.

NoSuchElementException may be suitable, but it is (at least by the JDK) mostly used for generic collection and container classes.

Maybe IllegalStateException would be more appropriate in your situation:

Signals that a method has been invoked at an illegal or inappropriate time. In other words, the [...] Java application is not in an appropriate state for the requested operation.

However, if you are designing a wrapper library, maybe defining your own exception class (possibly as part of an exception hierarchy) would be the best solution. This gives you all the freedom to decided whether the exception should be checked or not and give it a meaningful name. This way users of your library can directly see that the exception comes from your library and possibly be able to better handle the exception than a generic NoSuchElementException which could have been thrown by completely unrelated code as well.