0

Java Exceptions Practice 56.2 Category Handling Fails Test Case 4

I am having trouble with Java Exceptions Practice 56.2 Category Handling It is supposed to catch exceptions and output: "Wrong Option" I have tried a generic catch (exception e), I have also tried to catch NoSuchElementException instead of catching InputMismatchException I also tried just letting it throw an InputMismatchException on a non-integer input. I haven't been able to think of any test cases I didn't try in my IDE. import java.util.InputMismatchException; import java.util.Scanner; //fails test case 4 public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String[] categories = {"PCs", "Notebooks", "Tablets", "Phones", "Accessories"}; try { int choice = scanner.nextInt(); System.out.println(categories[choice]); } catch(ArrayIndexOutOfBoundsException | InputMismatchException e) { System.out.println("Wrong Option"); } } }

30th Aug 2022, 11:59 PM
Stephan Peters
Stephan Peters - avatar
2 Respuestas
+ 2
In the text : "Use the Exception type to catch all possible exceptions." So just use Exception class to catch exception => catch (Exception e) { ... } I have tried with ArrayIndexOutOfBoundsException, it works too test case 4 should print Accessories, check spelling in your code.
31st Aug 2022, 7:06 AM
Roland
Roland - avatar
+ 1
@Roland Yes, the problem was the "А" in "Аccessories" is Unicode \u0410 Cyrillic Capital Letter А in the provided code, instead of \u0041 Latin Capital Letter A. My code worked just fine as soon as I replaced A with А. The provided code will not catch a non-integer input (such as "A") as written, even with catch (Exception e) because int choice = scanner.nextInt(); is not in the try block, but there are no test cases with non-integer input.
31st Aug 2022, 2:11 PM
Stephan Peters
Stephan Peters - avatar