6

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
 }            
Raidri
  • 17,258
  • 9
  • 62
  • 65
Daniel Del Core
  • 3,071
  • 13
  • 38
  • 52
  • Is it appropriate to use an IllegalArgumentException? – Daniel Del Core Aug 25 '12 at 04:18
  • It seems that you have problem even with basic Java. You should read a good book before returning here, otherwise, it will be no less than copy and paste, which will teach you nothing. – nhahtdh Aug 25 '12 at 04:18
  • what was i doing wrong ? – Daniel Del Core Aug 25 '12 at 04:18
  • The switch case statement is not as per definition. – Vikdor Aug 25 '12 at 04:22
  • You don't have a switch statement, yet you're using `case`. Your method of gathering input is also suspect too. I agree with @nhahtdh in that you should read more tutorials before trying to delve deeper into exceptional behavior. – Makoto Aug 25 '12 at 04:22
  • `char choice = "0";` --> `"0"` is `String` object, not `char` - code should not compile. `choice != "q"` is bad, you want to compare value rather than reference - use `equals`. `System.in.read` - it is not usually the case that you read byte by byte for user input, you will usually wrap the `InputStream` (`System.in`) in `Scanner` and read by token or line by line. Your switch-case statement is missing the switch - and switch-case in Java only accept integral value or enum. Too many errors! – nhahtdh Aug 25 '12 at 04:23
  • My bad i forgot to type that in – Daniel Del Core Aug 25 '12 at 04:24
  • 1
    @DanielDC your question is rather unclear. Is it about how to use a switch statement? Is it how to syntactically use try/catch exceptions? Is it how to use try/catch statements well in practice? (they are different) You would do well to do some reading on exceptions, questions such as http://stackoverflow.com/questions/1084020/exceptions-and-abstractions and http://stackoverflow.com/questions/3115603/what-is-the-purpose-of-exceptions (in c# but same concept) or http://en.wikipedia.org/wiki/Exception_handling – Nathan Koop Aug 27 '12 at 03:05

2 Answers2

4

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.

gersonZaragocin
  • 1,122
  • 12
  • 20
  • As mentioned in the comments to the original question. The code provided is not valid. Here you have just copied pasted invalid code and made additions to it without fixing it. – anio Aug 25 '12 at 04:25
  • 1
    The thing is why should this method throw an exception? It is a loop to check the choice from the user, and it makes more sense to just print out the input is invalid and ask user to re-enter the input. – nhahtdh Aug 25 '12 at 04:26
  • Thanks for that it seems thats what i was after. I had the correct switch structure on my initial project but i typed it in wrong in the question. ill take more care next time – Daniel Del Core Aug 25 '12 at 04:28
  • @anio, yes you are right, i have added a comment here to explain my reason – gersonZaragocin Aug 25 '12 at 04:28
  • @nhahtdh, I guess he is just asking for the reasons behind using the exception handling mechanism. My explanation about different clients using the method is trying to put the real reason to use it. – gersonZaragocin Aug 25 '12 at 04:31
  • @gersonZaragocin: The scenario probably makes sense - I don't know about JSF so I didn't think about it. I interpret the question as OP wants to know how to do this for a cmd line program. Either way, the OP gives a horrible piece of Java code as example, and probably not specific enough if there are 2 different scenario (JSF and cmdline program). – nhahtdh Aug 25 '12 at 04:38
3

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);
 }
}