aquaduck97
aquaduck97
JCHJava Community | Help. Code. Learn.
Created by aquaduck97 on 9/27/2024 in #java-help
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
5 replies