mport java.io.*;
public class basic
{public static void main(String args[])
 {
   InputStreamReader ir;
   BufferedReader in;
   ir =new InputStreamReader(System.in);
   in =new BufferedReader(ir);
   int ranNum=(int)(Math.random()*10+1);
   int guessNum=-1;
   String str;
   while(guessNum!=ranNum)
   {
    try{
        System.out.print("Please Input:");
        str=in.readLine();  
        guessNum=Integer.parseInt(str);
       }
    catch(Exception e)
       {
       }
        if(guessNum>ranNum)
        System.out.print("Try smaller......");
     else
        System.out.print("Try bigger......");
  }
   System.out.print("Great!");
 }
}
我去掉try...catch..语句后:
mport java.io.*;
public class basic
{public static void main(String args[])  throws Exception
 {
   InputStreamReader ir;
   BufferedReader in;
   ir =new InputStreamReader(System.in);
   in =new BufferedReader(ir);
   int ranNum=(int)(Math.random()*10+1);
   int guessNum=-1;
   String str;
   while(guessNum!=ranNum)
   {
   
       System.out.print("Please Input:");
        str=in.readLine();  
        guessNum=Integer.parseInt(str);
       if(guessNum>ranNum)
        System.out.print("Try smaller......");
     else
        System.out.print("Try bigger......");
  }
   System.out.print("Great!");
 }
}

解决方案 »

  1.   

      第二个代码的public static void main(String args[])  throws Exception 是不是应该改成IOException?
      

  2.   

    第一段代码里,由于try子句中parseInt和readLIne都会抛出异常,所以要使用两个catch子句才能捕捉
        try{ 
            System.out.print("Please Input:"); 
            str=in.readLine();   
            guessNum=Integer.parseInt(str); 
           } 
        catch(IOException e) 
           { 
           //对应readLine()
           }
        catch(NumberFormatException e){
           //对应parseInt(str)
          }
    第二段代码里,你想不捕捉异常,把他吞掉,就要在main后面加上
    public static void main(String[] args)  throws IOException,NumberFormatException{
      //不用再写try catch子句
    }
    不过由于是main函数,已经没有代码能处理异常,使用不建议这样做。