站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2SE 专题不想输出null,覆盖父类方法

不想输出null,覆盖父类方法

摘要: 不想输出null,覆盖父类方法


class xx extends Exception {
public xx() {
System.out.println("除数为零");
}
}

class zz {
public int aa(int x, int y) throws xx {
if (y == 0)
throw new xx();
int reslut = x / y;
return x / y;
}
}

public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
zz z = new zz();
try {
int reslut = z.aa(3, 0);
System.out.println("the reslut is" + reslut);
} catch (xx xx) {
System.out.println(xx.getMessage());
//System.exit(0);
} catch (Exception e) {
System.out.println("program is running ");
return;
} finally {
System.out.println("I love you");
}
}
}





覆盖掉getMessage()方法就可以了

class xx extends Exception {
public xx() {
System.out.println("除数为零");
}
public String getMessage()
{
//System.out.println("is not null");
return "is not null";
}
}

这样就行了


解决了?


package csdn.dec;
class xx extends Exception {
public xx() {
System.out.println("除数为零");
}
}

class zz {
public int aa(int x, int y) throws xx {
int reslut = 0;
if (y == 0){
throw new xx();
}
else reslut = x / y;
return reslut;

}
}

public class Ttest {
public static void main(String[] args) {
// TODO Auto-generated method stubSystem.out.println("here?");
zz z = new zz();
try {
int reslut = z.aa(3, 0);
System.out.println("the reslut is"+ reslut );
} catch (xx xx) {
//System.out.println(xx.getMessage());
//System.exit(0);
} catch (Exception e) {
System.out.println("program is running ");
return;
} finally {
System.out.println("I love you");
}
}
}



下面是jdk的帮助
getMessage
public String getMessage()
Returns the detail message string of this throwable.

Returns:
the detail message string of this Throwable instance (which may be null).

所以你的Exception的子类成员要先覆盖父类,要不然它就返回null


是覆盖父类方法哈


使用super就可以了

例如:
========================================

class MyException extends Exception {
public MyException(String str) {
super(str);
}
};

public class Test {
public static void main(String[] args) {
try
{
throw new MyException("test by stefli");
}
catch (MyException ex)
{
System.out.println(ex.getMessage());
}

}
};


输出“test by stefli”



↑返回目录
前一篇: 获得引用
后一篇: http status 403-access to requested resource has been dennied