tags:

views:

106

answers:

5
public KalaGame(KeyBoardPlayer player1,KeyBoardPlayer player2)
 {   //super(0);
 int key=0;
 try
 {

     do{
     System.out.println("Enter the number of stones to play with: ");

      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  
        key = Integer.parseInt(br.readLine());  


    if(key<0 || key>10)
  throw new InvalidStartingStonesException(key);
  }
 while(key<0 || key>10);
    player1=new KeyBoardPlayer();
   player2 = new KeyBoardPlayer(); 
   this.player1=player1;
   this.player2=player2;
   state=new KalaGameState(key);



 }


    catch(IOException  e)
    {
       System.out.println(e);
      }
     } 

when i enter an invalid number of stones i get this error

Exception in thread "main" InvalidStartingStonesException: The number of starting stones must be greater than 0 and less than or equal to 10 (attempted 22)

why isn't the exception handled by the throw i defined at

KalaGame.<init>(KalaGame.java:27) at PlayKala.main(PlayKala.java:10)

+5  A: 

You are only handling an IOException but not the exception that is being thrown, i.e. an InvalidStartingStonesException.

Anthony Forloney
+1  A: 

You can catch multiple exception types and filter them accordingly:

try
{
 // ...
}
catch(IOException ioe)
{
 // ...
}
catch(Exception ex)
{
 // ...
}

You could add this last catch block to match any exception.

Alex
A: 

It sounds like it is being handled by the throw. By calling throw, you are telling Java "exit the program and print out the InvalidStartingStonesException". It sounds like this is what is happening. If you had the following:

catch(InvalidStartingStonesException{
   // code to handle the exception goes here
}

Then the program would run your error handling code. If this exception extended IOException you already have a catch there that would print the exception.

Jay Askren
A: 

i want to raise an exception when user enters invalid data and then again ask for the input. how do i do that

fari
This is not an answer to your question. You should edit the original question.
Jay Askren
A: 

The catch(IOException) block does not catch the exception, because InvalidStartingStonesException is not an IOException, neither a descendant of it.

Your exception is an unchecked exception, just as IllegalArgumentException is. The compiler does not obligate the programmer to catch such exceptions, since they usually represent bugs and not situations that can be handled.

Since the exception is not being caught, it propagates all the way down in the call stack of the main thread, until your program terminates.

Eyal Schneider