JAVA 异常处理练习

来源:互联网 发布:linux top res 编辑:程序博客网 时间:2024/04/30 19:37

//仅作为学习笔记


/* 异常练习1*/class NoValueException extends Exception{NoValueException(String msg){super(msg);}}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("出现非法值!");this.len = len;this.wid = wid;}public void getArea(){System.out.println(len*wid);}}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());}System.out.println("Over");}}



/* 异常练习2*/class NoValueException extends RuntimeException{NoValueException(String msg){super(msg);}}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("出现非法值!");this.len = len;this.wid = wid;}public void getArea(){System.out.println(len*wid);}}class ExceptionTest{public static void main(String [] args){Rec r = new Rec(-3,4);r.getArea();System.out.println("Over");}}


原创粉丝点击