Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A try-catch scenario - correct to use checked or not

Tags:

java

try-catch

I am looking at a code base where the domain model consists of many nested member variables.

Consider this scenario

private static String getSomeStringRepresentation(A input) {
    String result = "";
    try {
         result = input.getTypeA().getTypeAInfo().get(0).getRepresentation();
    } catch (NullPointerException e) {
        Logger.logDebug(e.getMessage());
    }
    return result;
}

In this call chain, any method call can result in a NullPointerException. Is it correct to handle it with a catch clause in this case? Is this a case where "it is possible to handle the exception" ?

Edit

The case of checking for null four times is really ugly. Don't you consider catching the NPE is justified in this case?

The problem here is calling some method on a object that possibly could be null.

like image 420
H.Rabiee Avatar asked Dec 02 '25 10:12

H.Rabiee


1 Answers

Why don't you check for null rather than putting a catch block? Catching NullPointerException isn't considered good practice.

If catching null pointer exception is not a good practice, is catching exception a good one?

also

Is Catching a Null Pointer Exception a Code Smell?

like image 161
gurvinder372 Avatar answered Dec 04 '25 23:12

gurvinder372