Null check in an enhanced for loop

What is the best way to guard against null in a for loop in Java?

This seems ugly :

if (someList != null) {
    for (Object object : someList) {
        // do whatever
    }
}

Or

if (someList == null) {
    return; // Or throw ex
}
for (Object object : someList) {
    // do whatever
}

There might not be any other way. Should they have put it in the for construct itself, if it is null then don’t run the loop?

11 Answers
11

Leave a Comment