开发者

I am getting exception in main thread...even when i am handling the exception

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 开发者_如何学Python= 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)


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


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜