Weird issue that gets solved by wrapping it in a try/catch but it never gets caught

I'm coming from C# and learning Java and I stumbled across a bit of a weird issue with String.startsWith and String.equals in foreach loops. I have a method to which I pass a String array, in this method I have a foreach loop that checks each string to a specific value using String.startsWith. If I DON'T wrap the loop in a try/catch I get an error that says the current array item is null when it doesn't match, but if I DO wrap it and put a breakpoint or println in the catch block, it's perfectly fine and I don't get any errors and the exception is never caught. The method (simplified):
public void compareString(String[] arr) {
String val = "";
boolean isValid = false;
do {
val = new Scanner(System.in).nextLine();
for(String word : arr) {
// Can print every word just fine
//Try/catch required here or errors at next line if sourcing "arr"
if(word.startsWith(val){ // Errors with null exception for "word" even though word is not null
isValid = true;
}
//Try/catch end
}
if(!isValid)
// Prints error
} while(!isValid);
public void compareString(String[] arr) {
String val = "";
boolean isValid = false;
do {
val = new Scanner(System.in).nextLine();
for(String word : arr) {
// Can print every word just fine
//Try/catch required here or errors at next line if sourcing "arr"
if(word.startsWith(val){ // Errors with null exception for "word" even though word is not null
isValid = true;
}
//Try/catch end
}
if(!isValid)
// Prints error
} while(!isValid);
If I hardcoded an array in the method it worked perfectly fine without a try/catch
3 Replies
JavaBot
JavaBot2mo ago
This post has been reserved for your question.
Hey @aquaduck97! Please use /close or the Close Post button above when your problem is solved. 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.
aquaduck97
aquaduck97OP2mo ago
I made the original array bigger and left an empty spot, hence the error when it didn't match since it reached the last item which was null. Not proud of that one 🙂
JavaBot
JavaBot2mo ago
Post Closed
This post has been closed by <@132578861765492736>.
Want results from more Discord servers?
Add your server