NullPointerException or if statement

This isn’t really a problem I have, more of a question of what’s considered good practice. I recently realized that I can catch NullPointerExceptions, instead of using a if statement. So far I have only used it in places where I expect to not need and if statement, but I wonder is it right? and if not, when should I catch NullPointerException instead of using if’s?

There is one place where I used it like this

try{
    renderComponent[RENDER_BG].getImage().render(g2, x, y+7);
    renderComponent[RENDER_NAME].getImage().render(g2, x+5, y);
    renderComponent[RENDER_DATE].getImage().render(g2, 30+(textBreakWidth*1), y);
    renderComponent[RENDER_TIME].getImage().render(g2, (textBreakWidth*2)-renderComponent[RENDER_TIME].getImage().getWidth()+20, y);
}catch(java.lang.NullPointerException e){
    showingAnimation = false;
}

instead of

if(     renderComponent[RENDER_BG].getImage() != null &&
        renderComponent[RENDER_NAME].getImage() != null &&
        renderComponent[RENDER_DATE].getImage() != null && 
        renderComponent[RENDER_TIME].getImage() != null){
    renderComponent[RENDER_BG].getImage().render(g2, x, y+7);
    renderComponent[RENDER_NAME].getImage().render(g2, x+5, y);
    renderComponent[RENDER_DATE].getImage().render(g2, 30+(textBreakWidth*1), y);
    renderComponent[RENDER_TIME].getImage().render(g2, (textBreakWidth*2)-renderComponent[RENDER_TIME].getImage().getWidth()+20, y);
}else{
    showingAnimation = false;
}

In situations like that I feel like the try statement is much more useful than a if, it also makes the code a lot more readable.

The if statements all the way. If the first two elements aren’t null and the third one is you will have wasted the time it takes to call the two render methods and you may get render artifacts in the result.

Also, entering try clauses is quick, catching exceptions is slow :slight_smile:

Mike

First note that these two are not equivalent. The try version will do everything until any failure where the if version only does something if no failure will occur. What I’d suggest is neither and disallow getImage to ever return null.

Exceptional circumstance - > Exception

Missing resources is a perfectly acceptable example, though checking that they loaded properly in the first place is preferable (but not always possible).

Thanks, I didn’t think of that.