java编程初学的问题

来源:百度知道 编辑:UC知道 时间:2024/05/22 03:08:14
class DevideByMinusException extends Exception
{ String ms;
public DevideByMinusException(String ms)
{this.ms=ms;}
public DevideByMinusException()
{}

}

class Test
{
public int devide(int x,int y) throws Exception
{
if(y<0)
{throw new DevideByMinusException("错误"); }
else
return 1;

}
}

class TestException
{
public static void main(String [] args)
{
try{
new Test().devide(3,-1) ;
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println("running");

}

}
为什么运行后显示的是null而不是“错误”,当第4行改成super语句后就好了,也许是有关继承方面的知识点,希望帮忙,请详细点,我刚学编程几天,见谅

你可以把try{
new Test().devide(3,-1) ;
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
再成:try{
new Test().devide(3,-1) ;
}
catch(DevideByMinusException e)
{
System.out.println(e.getMessage());
}
因为你要用的是自己的类,所以最好是改成这样,

兄弟,你的错误类虽然继承了exception,但在构造时没有调用exception的构造方法,你的错误消息只存在于字定义错误类中,父类当然调不到啦

class DevideByMinusException extends Exception {
String ms;

public DevideByMinusException(String ms) {
super(ms);//这里调用父类构造方法
this.ms = ms;
}

public DevideByMinusException() {
}

}

class Test {
public int devide(int x, int y) throws Exception {
if (y < 0) {
throw new DevideByMinusException("错误");
} else
return 1;

}
}

class TestException {
public static void main(String[] args) {
try {
new Test().devide(3, -1);