/* 有一个圆形和长方形。 都可以获取面积。对于面积如果出现非法的数值,视为是获取面积出现问题。 问题通过异常来表示。 现有对这个程序进行基本设计。 */ //自定义异常 class NoValueException extends RuntimeException { NoValueException(String message) { super(message); } } interface Shape { void getArea(); } class Rec implements Shape { private int len,wid; Rec(int len,int wid)//throws NoValueException { if(len<0 || wid<0) throw new NoValueException("出现负数了"); //注意new else { this.len=len; this.wid=wid; } } public void getArea() { System.out.println(len*wid); } } class Circle implements Shape { private int redius; public static final double PI = 3.14; Circle(int redius) { if(redius<=0) throw new NoValueException("出现负数了"); this.redius=redius; } public void getArea() { System.out.println(redius*redius*PI); } } class ExceptionTest { public static void main(String[] args) { //try //{ Rec r = new Rec(3,4); r.getArea(); //} //catch (NoValueException e) //{ //System.out.println(e.toString()); //} Circle c = new Circle(-3); c.getArea(); } }体会:时隔n长时间,重返csdn。再次找到熟悉的感觉~~
原文:http://blog.csdn.net/qxuewei/article/details/22962055