#How to throw null errors

15 messages · Page 1 of 1 (latest)

wooden pecan
#

So I am trying to check if many strings are null and then throw an error for the one/ones that are. This is currently what I have right now except there are many more strings and I don't want to do this for all of them.

`String STRING_1, STRING_2, STRING_3, STRING_4 = null;

try (FileInputStream fileInputStream = new FileInputStream(PROPERTIES_FILENAME)) {
properties.load(fileInputStream);
STRING_1 = properties.getProperty("string1");
STRING_2 = properties.getProperty("string2");
STRING_3 = properties.getProperty("string3");
STRING_4 = properties.getProperty("string4");
if (STRING_1 == null || STRING_2 == null || STRING_3 == null || STRING_4 == null) {
System.err.println(STRING_1 == null ? "string1 is null!" : "");
System.err.println(STRING_2 == null ? "string2 is null!" : "");
System.err.println(STRING_3 == null ? "string3 is null!" : "");
System.err.println(STRING_4 == null ? "string4 is null!" : "");

    System.exit(1);
}

}`

sturdy trailBOT
#

This post has been reserved for your question.

Hey @wooden pecan! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

polar lynx
#

to throw an exception in java, use the throw keyword and then reference a Throwable object

#

in your case probably a NullPointerException, so something like if(STRING_1 == null) throw new NullPointerException("String1 is null");

#

for iteration, you could enclose the strings in a temporary list like this:
for (String s : List.of(STRING_1, STRING_2, STRING_3, STRING_4))

#

actually nevermind, you can't do that, because List.of() doesn't accept null values

rocky igloo
#

I take it you want to list all of those that are null, rather than fail at the first moment you find one that is?

polar lynx
#

maybe, but they did specifically say they wanted to "throw" an error

rocky igloo
#

yes, beginners don't know the words. I do hold it against them when they clearly should have realized they lack proper vocabulary and they should have explained themselves.
But when that's secondary to the problem I deal with it and I suggest you do too, like by asking precisions like I did

wooden pecan
rocky igloo
#

You need to make a method that takes as parameters the String you want and the Properties object.
This method gets that String from the Properties, checks whether it is null, adds it to a set of found null values if so,
and if not returns the value found in Properties

#

In other words, it's not magic. To make it cleaner you must program so. I don't know a secret you didn't know, but admittedly the reflex to program stuff is easier on me.

wooden pecan
#

OK thanks @polar lynx @rocky igloo

sturdy trailBOT