黑马程序员技术交流社区

标题: Exception中的特殊子类异常RuntimeException [打印本页]

作者: 池中月    时间: 2015-7-4 21:43
标题: Exception中的特殊子类异常RuntimeException
RuntimeException:运行时异常


1、使用特点之处:

原因:
      因为不需要让调用者处理;当异常发生希望程序停止,或是在运行时出现了无法继续运行的错误,希望停止程序后对代码修改;
  1. package unit12;

  2. interface shape{//定义接口shape,包含抽象方法getAre
  3.         public double getAre();
  4. }
  5. //自定义非法数值异常,继承RuntimeException,故,在函数声明是不用声明异常类
  6. class IllegalException extends RuntimeException{
  7.         public IllegalException(String message) {
  8.                 super(message);
  9.         }
  10. }


  11. //定义圆形类,实现接口shape
  12. class Round implements shape{
  13.         private double radius;
  14.         public static double PI = 3.14;
  15.         Round(double radius){
  16.                 this.radius = radius;
  17.                 if(radius <=0)    //半径小于0时,抛出异常
  18.                         throw new IllegalException("数值非法");
  19.         }
  20.         public double getAre(){
  21.                 return radius*radius*PI;
  22.         }
  23.        
  24. }
  25. //自定义长方形类,实现接口shape
  26. class Rectangle implements shape{
  27.         private double longs;
  28.         private double high;
  29.         Rectangle(double longs, double high){
  30.                 this.longs = longs;
  31.                 this.high = high;
  32.                 if(longs<=0 || high<=0)//长或高小于0是抛出异常
  33.                         throw new IllegalException("非法");
  34.         }
  35.        
  36.         public double getAre(){
  37.                 return longs*high;
  38.         }
  39. }

  40. public class ExceptionTest2 {
  41.         public static void main(String args[]){
  42.         try{
  43.                 Round r = new Round(12.2);//初始化圆形对象是可能发生异常
  44.                 System.out.println("圆形面积为:"+r.getAre());
  45.         }catch(IllegalException e){
  46.                 System.out.println(e.toString());
  47.         }
  48.         try{
  49.                 Rectangle rc = new Rectangle(0,34);//初始化长方形对象时可能发生异常
  50.                 System.out.println("长方形面积为:"+rc.getAre());
  51.         }catch(IllegalException e){
  52.                 System.out.println(e.toString());
  53.         }
  54.        
  55.         }
  56.        

  57. }
复制代码












欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2