日期:2014-05-20  浏览次数:20691 次

写代码遇到了Exception的问题,向高手求救!
下面是个test异常的代码,但不知为何只输出了“被除数和除数相等的异常信息”,除数为零,和数组越界都没输出,在了很久都没找出错在哪里;还有运行结果的那个null是怎么回事?
请给为高手指点!!



package e;
import java.lang.Exception;

class MyException extends Exception{
int x;
int y;
int i;
  public MyException(int y,int x){
  this.y=y;
  this.x=x;
  }
  public MyException(String ss){
  System.out.println(ss);
  }
  public MyException(String s,int y,int x){
  System.out.println(s+" "+y+" "+x);
  }
  public MyException(String s,String ss,int i,String sss){
  System.out.println(s+" "+ss+i+sss);
  }
  public int getxy(int y,int x){
  String s=Integer.toString(y);
String ss=Integer.toString(x);
String sss=s+ss;
return Integer.parseInt(sss);
  }  
}

class LX11_1 {
static int x;
static int y;
static int i;
static int ii;
static int n=1;

public LX11_1(){}
public int f(int x,int y) throws MyException {
this.y=y;
  this.x=x;
if(y==0) throw new MyException("除数为零!");
if(y==x) throw new MyException("被除数和除数相等!",y,x);
n = y/x; 
System.out.println(n);
return n;
}
static int[] a={1,2,3,4,5,};
 
public int g(int i) throws MyException{
  this.i=i;
  if(i>4&&i<0) throw new MyException("数组下标越界!","int[",i,"]"); //ArrayIndexOutOfBoundsException(); //
  int ii =a[i];
  System.out.println("int["+i+"]="+ii);
return ii;
}

public static void main(String[] args){
try{
LX11_1 lx=new LX11_1();
int n1=lx.f(3,6);
System.out.println(n1); //这样才会输出n。
int n2=lx.f(3,3);
int n3=lx.f(3,0);
}  
catch(MyException e1){
// System.out.println("被除数和除数相等!");
System.out.println("相等!"+e1.getxy(y,x));
System.out.println(e1.getMessage());
}
try{
LX11_1 lx1=new LX11_1();
int n3=lx1.g(2);
System.out.println(n3);
int n4=lx1.g(6);
int n5=lx1.g(-2);
}
catch(MyException e3){
System.out.println("数组下标越界!");
System.out.println(e3.getMessage());
}
}
}


运行情况:
2
2
被除数和除数相等! 3 3
相等!33
null
int[2]=3
3
3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:6
  at e.LX11_1.g(lx11_1.java:53)
  at e.LX11_1.main(lx11_1.java:75)


不是写了throw怎么还会说还有异常没出来?还有那个null是怎么回事啊??

------解决方案--------------------
代码写的太乱,看了半天。
1.只输出了“被除数和除数相等的异常信息”。这个是因为try块里语句抛出异常,这条语句后边就不会执行了。
2.输出null是因为。System.out.println(e3.getMessage());这句。e3.getMessage()返回空。你可以在构造方法里调用super(String message)的构造方法。
3.最后直接打印了异常信息是因为 这句if(i>4&&i<0)根本无法为真。直接抛出ArrayIndexOutOfBoundsException了。