package exceptiontest2; /** * *代码描述: *有一个圆Circle和长方形Rec *都可以获取图形的面积getArea() *对于计算面积过程中出现非法值value<0,视为出现问题 *问题用异常NoValueException来描述, *且其继承RuntimeException * 流程代码和处理代码进行分离 * * * 不用if判断 * 因为if判断就算计算参数是错的,它会默认给length和high赋默认值0 * 仍会面积计算 * 但实际错误后应该进行提示,并不会调用getArea() * 问题用异常来解决 * * @author Administrator * */ public class ExceptionTest2 { public static void main(String[] agrs) { // try { Rec r = new Rec(4, 4); // Rec p = new Rec(-4, 4); r.getArea(); // p.getArea(); // } catch (NoValueException e) { // // TODO Auto-generated catch block // System.out.println(e.toString()); // // } Cicrle c = new Cicrle(-1); c.getArea(); System.out.println("over"); } }
package exceptiontest2; public class NoValueException extends RuntimeException { NoValueException(String message) { super(message); } }
package exceptiontest2; public interface Shape { public void getArea(); }
package exceptiontest2; public class Rec implements Shape { private int length; private int high; Rec(int len, int hig) {// throws NoValueException { this.length = len; this.high = hig; if (length < 0 || high < 0) throw new NoValueException("输入非法值"); } public void getArea() { // TODO Auto-generated method stub System.out.println(length * high); } }
package exceptiontest2; public class Cicrle implements Shape { private int radium; public static final double PI = 3.14; public Cicrle(int radium) { if (radium < 0) throw new NoValueException("非法"); this.radium = radium; } @Override public void getArea() { // TODO Auto-generated method stub System.out.println(radium * radium * PI); } }
参考文献:传智播客毕向东Java基础视频教程-day10-04-面向对象(异常-练习)