public class Exceptionadd {
   private int a;
   private int b;
   public int devide(int a,int b){
     return a/b;
   }
   public int add(int a,int b){
     return a+b;
   }}
public class TestException {
  public static void main(String[] args) {
    // TODO Auto-generated method stub
            int a=Integer.parseInt(args[0]);
            int b=Integer.parseInt(args[1]);
            Exceptionadd exception=new Exceptionadd();
            try{
              exception.devide(a,b);
            }
            catch(Exception e){}
            
  }}
 如果a,b不能为自符串,字母,只能为数字,怎么捕捉这个错误!

解决方案 »

  1.   

    int a;
    int b;
    try{
      a = Integer.parseInt(args[0]);
    }catch(Exception ex){
      // a 不能解析成数字
    }
    try{
      b = Integer.parseInt(args[1]);
    }catch(Exception ex){
      // b 不能解析成数字
    }
      

  2.   

    public   class   Exceptionadd   { 
          private   int   a; 
          private   int   b; 
          public   int   devide(int   a,int   b){ 
              return   a/b; 
          } 
          public   int   add(int   a,int   b){ 
              return   a+b; 
          } } public class TestException {
      public static void main(String[] args) {
        // TODO Auto-generated method stub
                int a;
                int b;
                Exceptionadd exception=new Exceptionadd();
               try{
                       a=Integer.parseInt(args[0]);
                       b=Integer.parseInt(args[1]);
                        try{ 
                         System.out.println("a/b="+ exception.devide(a,b));
                         }
                       catch(Exception e){
                         System.out.println("除法分母不能为零!");
                       }
                       
                       System.out.println("a+b="+exception.add(a,b));
                       
               }
               catch(Exception e){
                 System.out .println("请输入两个数字!");
               }
               
    }
    }
      

  3.   

    int a,b;
    try {    
      a=Integer.parseInt(args[0]); 
      b=Integer.parseInt(args[1]); 
    } catch(NumberFormatException e) {
      System.out.println("请输入数字");
      System.exit(-1);
    }