RuntimeException:运行时异常
1、使用特点之处:
- 如果在函数内抛出该异常,函数上不用声明,编译一样通过;
- 如果在函数上声明了该异常,调用者可以不用处理,编译一样通过
原因:
因为不需要让调用者处理;当异常发生希望程序停止,或是在运行时出现了无法继续运行的错误,希望停止程序后对代码修改;
- package unit12;
- interface shape{//定义接口shape,包含抽象方法getAre
- public double getAre();
- }
- //自定义非法数值异常,继承RuntimeException,故,在函数声明是不用声明异常类
- class IllegalException extends RuntimeException{
- public IllegalException(String message) {
- super(message);
- }
- }
- //定义圆形类,实现接口shape
- class Round implements shape{
- private double radius;
- public static double PI = 3.14;
- Round(double radius){
- this.radius = radius;
- if(radius <=0) //半径小于0时,抛出异常
- throw new IllegalException("数值非法");
- }
- public double getAre(){
- return radius*radius*PI;
- }
-
- }
- //自定义长方形类,实现接口shape
- class Rectangle implements shape{
- private double longs;
- private double high;
- Rectangle(double longs, double high){
- this.longs = longs;
- this.high = high;
- if(longs<=0 || high<=0)//长或高小于0是抛出异常
- throw new IllegalException("非法");
- }
-
- public double getAre(){
- return longs*high;
- }
- }
- public class ExceptionTest2 {
- public static void main(String args[]){
- try{
- Round r = new Round(12.2);//初始化圆形对象是可能发生异常
- System.out.println("圆形面积为:"+r.getAre());
- }catch(IllegalException e){
- System.out.println(e.toString());
- }
- try{
- Rectangle rc = new Rectangle(0,34);//初始化长方形对象时可能发生异常
- System.out.println("长方形面积为:"+rc.getAre());
- }catch(IllegalException e){
- System.out.println(e.toString());
- }
-
- }
-
- }
复制代码
|
|