首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Eclipse开发 >

关于java错误处理有关问题

2012-09-22 
关于java异常处理问题。Java codeclass TooFewLegsError extends Exception{private int legspublic TooFe

关于java异常处理问题。

Java code
class TooFewLegsError extends Exception  {  private int legs;  public TooFewLegsError(int l){legs=l;}  public int getLegs(){return legs;} }  class ZeroSideError extends Exception   {    private int sides;    public ZeroSideError(){};    public int getSides(){return sides;}  }  class IrregularShapeError extends Exception  {    private int shapes;    public IrregularShapeError(){}    public int getShapes(){return shapes;} }  class Table {  private int shape;  private int legs;  private int sides;  public Table(int shape1,int s,int l) throws TooFewLegsError, ZeroSideError, IrregularShapeError  {   if(l<4)    throw new TooFewLegsError(l);   else if(s<=0)    throw new ZeroSideError();   else if(shape==4)    throw new IrregularShapeError();   else    shape=shape1;    legs=l;    sides=s;  }    public void setLegs(int l) throws TooFewLegsError  {   if(l<4)    throw new TooFewLegsError(l);  }    public void setSides(int s) throws ZeroSideError  {   if(s<=0)    throw new ZeroSideError();  }      public void setShape(int shape1) throws IrregularShapeError     {      if(shape==4)       throw new IrregularShapeError();      else       shape=shape1;     }          public static void main(String argv[])     {      try {            Table t=new Table(3,-2,0);            t.setShape(3);            t.setSides(-2);            t.setLegs(0);         }         catch (IrregularShapeError n) {            System.out.println(                 "不可能有不规则的桌子。");          }         catch (TooFewLegsError n) {            System.out.println("桌腿数量错误。" + n.getLegs()                  + "条腿的桌子不存在.");         }         catch (ZeroSideError n) {            System.out.println(               "桌子不能有0个角");          }     } }


这是自己照着书修改之后的结果。之前那个帖子关了。
我希望达到的效果是执行t.setShape(3)和t.setSides(-2),但不知道为什么执行的会是t.setLegs(0)。
异常处理我也明白一点点,但就是不知道为什么执行的结果跟我预期的相反。
请高手帮忙改成抛出t.setShape(3)和t.setSides(-2),不执行t.setLegs(0)。
谢谢了!

[解决办法]
Java code
 public void setShape(int shape1) throws IrregularShapeError     {      if(shape==3)       throw new IrregularShapeError();      else       shape=shape1;     }public void setSides(int s) throws ZeroSideError  {   if(s<=0)    throw new IrregularShapeError();  } 

热点排行