黑马程序员技术交流社区

标题: java异常问题,很简单的,大家看下为什么达不到预期效果 [打印本页]

作者: 337091921    时间: 2013-4-27 02:15
标题: java异常问题,很简单的,大家看下为什么达不到预期效果
本帖最后由 337091921 于 2013-5-11 21:43 编辑

public class Exception3 {  
public static int Sum(int n){
if(n<0)   throw new IllegalArgumentException("n应该为整数");  
int s=0;  
for(int i=0;i<=n;i++)
s+=i;  return s;
}
public static void main(String args[])
{
  try{   int n=Integer.parseInt(args[0]);
  System.out.println(Sum(n));
  }  catch(ArrayIndexOutOfBoundsException e)
{   
System.out.println("命令行为:"+"javaException3<number>");
  }  catch(NumberFormatException e2)
{
System.out.println("参数<number>应为整数!");
}  catch(IllegalArgumentException e3)
{
System.out.println("错误参数:"+e3.toString());
}
finally{System.out.println("程序结束");
}
}
}/*如果运行改程序的命令行输入为:java Exception3  屏幕显示为:java Exception3<number> 程序结束 如果命令行输入为:java Exception3 -4 屏幕显示为: 参数错误:java.long.IllegalAgumentException:n 应该为整数! 程序结束 可是程序运行时 跑出和捕获异常根本不起作用*/
作者: breeze    时间: 2013-4-27 20:49
你的Sum(int n) 方法没有把异常抛出, 应该是下面这样
public class Exception3 {
        public static int Sum(int n) throws IllegalArgumentException {
                if (n < 0)
                        throw new IllegalArgumentException("n应该为整数");
                int s = 0;
                for (int i = 0; i <= n; i++)
                        s += i;
                return s;
        }

        public static void main(String args[]) {
                try {
                        int n = Integer.parseInt(args[0]);
                        System.out.println(Sum(n));
                } catch (ArrayIndexOutOfBoundsException e) {
                        System.out.println("命令行为:" + "javaException3<number>");
                } catch (NumberFormatException e2) {
                        System.out.println("参数<number>应为整数!");
                } catch (IllegalArgumentException e3) {
                        System.out.println("错误参数:" + e3.toString());
                } finally {
                        System.out.println("程序结束");
                }
        }
}




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2