简体   繁体   中英

Return value in getter method if object not found

I am wondering what is the best design for this problem. I have a Season object which which has an ArrayList<Episode> which contains every episode in a season for a given TV show. Now let's say I want to search for episode 25 of a given season for a given TV show. Is the following design appropriate (throwing an Exception) or would it be better to create an object in a state of error, return that and let the calling method figure what's wrong ?

public class Season {
    public Episode GetEpisode(int ep_no) throws Exception {
        for(Episode ep : episodes)
            if(ep.GetEpisodeNumber() == ep_no) return ep;
        throw(new Exception("Episode not found."));
    }

    private ArrayList<Episode> episodes;
}

It depends. First of all, I wouldn't throw a bare Exception . I'd create a new type of exception. Perhaps an EpisodeNotFoundException . That way it's more descriptive.

Second, does the code need to handle this situation when it occurs, or is it something that shouldn't fail. If it would require programmer intervention, you should throw an exception that extends RuntimeException instead. Code that throws RuntimeException does not need to be handled by the code that calls it.

Also, is it an error if an episode isn't found, or is it a completely acceptable thing to occur? If it's acceptable, you should probably return null instead. This is the way Map.get() works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM