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
}
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
choiceOptionyou should do this: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
InvalidInputExceptionis a class that have to extend Exception.