JAVA学习笔记之四

来源:互联网 发布:网络文字顶格 编辑:程序博客网 时间:2024/05/29 17:21

今天就简单聊聊JAVA中的异常


很多时候,我们在C,C++ 会碰到一些异常参数的传入或者返回一些异常状态。对此我们可以通过得到函数的返回值,根据函数的返回值来决定进程是否执行。


在JAVA这种面向对象编程中把这种特性可以说发挥到极致。JAVA把这些异常都封装成了类。

如果自定义个一个异常类 必须继承异常类  才可以具备可抛性  才可以被throws throw两个关键字操作


这里说明一下throw throws的区别

1、throw 使用函数内 抛出的是异常对象
2、throws 使用函数 抛出的是异常类 可以抛出多个,用逗号隔开


当然也不是所有的异常类的使用的时候都需要throws

我们还可以发现检测异常类的时候还分为两类

1、编译时检测异常,除了RuntimeException
这种问题的发生,希望编译时进行检测,让问题有对应的处理方式
2、运行时检测异常 就是RuntimeException
这种问题的发生,无法让功能继续,运算无法进行,更多是因为调用者导致的,或者是引发了内部状态的原因产生的。
这种问题一般不处理,直接编译通过,在运行的时候,使用代码强制停止——简而言之,就是不需要throws。


class FushuIndex extends Exception {FushuIndex(){         }FushuIndex(String msg){super(msg);}}class Demo {public int methos(int arr[],int index) throws FushuIndex{if(index >= arr.length)//not RuntimeException{ throw new FushuIndex(" index beond the length");}if(index < 0)// is RuntimeException{throw new ArrayIndexOutOfBoundsException("negative number");} return arr[index];}}class Test2 {public static void main(String[] args) throws FushuIndex{//int[] array = new int[3];Demo d =new Demo();d.methos(array,3);//System.out.println("Hello World!");}}


OUTPUT:

        

       Exception in thread "main" FushuIndex:  index beond the length

       因为检测到的异常是继承从Exception类,所以需要throws ,并且在编译的时候就检测出来。

      如果继承自 RuntimeException类,编译的时候可以通过,运行的时候就检测到并一直抛出到mian * 最后到达虚拟机控制台。





0 0
原创粉丝点击