一道简单的JAVA练习题关于异常的
public Mult1(double result)throws LessThanZeroException 没有返回值,至少应该定义个void另外main()方法应该放在public的类里吧修改后的代码(没用到Mult1()方法)class LessThanZeroException extends Exception { public LessThanZeroException(String s) { super(s); } public LessThanZeroException() { this(""); } }public class Mult1 { protected double result; public void Mult1(double result)throws LessThanZeroException { t(result); } public void set(double result) throws LessThanZeroException { if(result<0) throw new LessThanZeroException(""+result); } public static void main(String args[]) { double m=4; double n=0。
2; double result=m*n; try { if(result<0) {throw new LessThanZeroException();}} catch(LessThanZeroException e) { intln("产生乘积小于0异常!"); } finally { intln("乘积为"+result); } } }。
哪边 你抛异常 try那个哎试试 new Mult1(result);
二楼的朋友 Mult1()是构造方法,需要void?。。。 ============================================== 因为main为static(静态)方法,静态方法只能调用静态方法和静态属性 你可以在Mult1和set方法前加个static,当然,main方法所在的类应该为public类型,而一个类文件中也不可以存在两个public class 所以将前面的public去掉吧,然后在main中调用就可以了,例如: class LessThanZeroException extends Exception { LessThanZeroException(String s) { super(s); } LessThanZeroException() { this(""); } } public class Mult1 { protected double result; public static void Mult1(double result) throws LessThanZeroException { t(result); } public static void set(double result) throws LessThanZeroException { if (result < 0) throw new LessThanZeroException("" + result); } public static void main(String args[]) { double m = 4; double n = 0。
2; double result = m * n; try { Mult1。
Mult1(result); } catch (LessThanZeroException e) { intln("产生乘积小于0异常!"); }catch(Exception e){ intStackTrace(); }finally { intln("乘积为" + result); } } }。