Java Exception Handling Invalid input

40,439

Solution 1

I am assuming that your errors are deliberated so I will use your own code to make a sample of the usage you are asking for. So it is still your responsibility to have a running program.

Exception Handling mechanism is done to let you throw Exceptions when some error condition is reached as in your case. Assumming your method is called choiceOption you should do this:

public void choiceOption() throws InvalidInputException {
    char choice = "0";

    while (choice != "q"){
        printMenu();

        System.in.read(choice);
        switch(choice){
        case "1": DisplayNumAlbums();
        case "2": ListAllTitles();
        case "3": DisplayAlbumDetail();
        case "q": System.out.println("Invalid input...");
                  return;
        default: System.out.println("Invalid input...");
                 throw new InvalidInputException();
        }
    }
}

This let you catch the thrown Exception in the client side (any client you have: text, fat client, web, etc) and let you take your own client action, i.e. Show a JOptionPane if you are using swing or add a faces message if you are using JSF as your view technology.

Remember that InvalidInputException is a class that have to extend Exception.

Solution 2

if your code is inside a method, you can state that the method throws exceptions,

void method throws Exception(...){}

and the invocation of the method must be in a try-catch block

try{
 method(...);
}catch(SomeException e){
 //stuff to do
}

or you can just

while(){
 ...
 try{
  case...
  default:
   throw new IllegalArgumentException("Invalid input...");
 }catch(IllegalArgumentException iae){
  //do stuff like print stack trace or exit
  System.exit(0);
 }
}
Share:
40,439
Daniel Del Core
Author by

Daniel Del Core

Updated on June 05, 2020

Comments

  • Daniel Del Core
    Daniel Del Core almost 4 years

    I'm trying my hand at Java's exception handling.

    I can't understand how to do this from the docs, but what I want to do is detect invalid input for my switch to throw an error when the default case is activated. This may be incorrect logic on my part, but I wonder if any one could push me in the right direction in plain English.

    char choice = '0';
    while (choice != 'q'){
         printMenu();
         System.in.read(choice);
    
         case '1': DisplayNumAlbums();
         case '2': ListAllTitles();
         case '3': DisplayAlbumDetail();
         case 'q': System.out.println("Invalid input...");
         return;
         default: System.out.println("Invalid input...");
         //Exception handling here
         //Incorrect input
     }