End method in normal flow versus exception flow

  softwareengineering

Consider the two following examples:

public Something fetchSomething(String key) {
    if(somethingsMap.containsKey(key)) {
        return somethingsMap.get(key);
    }

    throw new IllegalStateException("key is missing");
}

versus

public Something fetchSomething(String key) {
    if(!somethingsMap.containsKey(key)) {
        throw new IllegalStateException("key is missing");
    }

    return somethingsMap.get(key);
}

Is there any general consensus which is considered “better”/more clean/preferred. Ending in normal flow or ending in exception flow.
Or is this solely opinionated?

New contributor

steros is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT