Search code examples
javaexceptionmethodsunchecked-exception

Custom Unchecked Exceptions


Okay guys I've been trying to figure this out for the past day or so. My homework assignment has me creating both Unchecked and Checked Exceptions. The checked exceptions I believe I get basically they must be handled before compiling (With try & catch or throwing it to the next thing that calls it. For unchecked exceptions I don't understand how custom ones work. They are caught at runtime and don't necessarily need to be thrown or encased with try & catch but if they're custom how does the IDE or whatever know what to look for? Example: One of my custom Unchecked files is supposed to trigger if the user adds a pokemon but the party is full, but how do I tell the IDE that that's what needs to happen? My Exception file looks like:

public class PartyIsFullException extends RuntimeException {

    public PartyIsFullException() {
        super();
    }

    public PartyIsFullException(String message) {
        super(message);
    }
}

and then I want to implement it in this method, but idk how to do it. I realize now I can't throw them because the user won't be expecting them and therefore won't try to catch them.

public void addToParty(String name) throws PartyIsFullException {
        boolean exists = false;
        for (int i = 0; i < 152; i++) {
            exists = (name.equals(pokedex[i]));
        }
        if (exists) {
            throw new PokemonAlreadyExistsException();
        } else {
            if (partyPos < 6) {
            party[partyPos] = name;
            partyPos++;
            } else {
                throw new PartyIsFullException();
            }
        }
    }

Solution

  • I realize now I can't throw them because the user won't be expecting them and therefore won't try to catch them.

    You can throw them!

    In a real project, it should be clearly documented.

    /*
     * @throws PartyIsFullException if isPartyFull() would return true
     */
    public void addToParty(String name) throws PartyIsFullException {...}
    

    Usually an unchecked exception is used for a situation where the client of the method is avoiding the exceptional condition themselves e.g.:

    if(theParty.isPartyFull()) {
        // tell the user the party is full
        // and they can't add more Pokemon
    } else {
        theParty.addToParty(thePokemon);
    }
    

    And thus they shouldn't have to explicitly catch it because they are already handling that circumstance.

    If the exception is thrown and there is not a try-catch outside, it will throw all the way up to terminate the thread. (For a small program with just main, this means the program crashes.)