异常
- 异常的体系
1.Throwable
Error:通常出现重大问题,如:运行的类不存在或内存溢出等。
不编写针对代码对其处理。
Exception:在运行时出现的情况,可以通过try catch finally
Error和Exception的子类名都是以父类名作为后缀。
在Java中用类的形式对不正常情况进行了描述和封装对象,这就称为异常类。
异常就是Java通过面向对象思想将问题封装成了对象。 - 可抛性:
凡是被throws、throw两个关键字操作的类和对象都具备可抛性。 - 抛异常:
class Demo{
public int method(int[] arr,int index){
if(arr == null){
throw new NullPointerException("数组不能为空!");
}
if(intdex >= arr.length){
throw new ArrayIndexOutOfBoundsException("数组角标越界"+index);
}
}
}
class Demo2{
public static void mian(String[] args){
int[] arr=new int[3];
Demo d=new Demo();
int num=d.method(arr,30);
}
}
- 自定义异常:
- 注意:
如果让一个类称为异常类,必须要继承异常体系,因为只有成为异常体系的子类才有资格具备可抛性,被throws和throw操作。
class FuShuIndexException extends Exception{
FuShuIndexException(){}
FuShuIndexException(String msg){
super(msg);
}
}
class Demo{
//抛出异常声明
public int method(int[] arr,int index) throws FuShuIndexException{
if(arr == null){
throw new NullPointerException("数组不能为空!");
}
if(intdex >= arr.length){
throw new ArrayIndexOutOfBoundsException("数组角标越界"+index);
}
if(index < 0){
//为报告的异常,必须进行捕捉或声明
//throw new FuShuIndexException();
throw new FuShuIndexException("数组角标不能为负!");
}
return arr[index];
}
}
class Demo2{
//抛出异常声明,所有调用的类都需要声明
public static void mian(String[] args) throws FuShuIndexException{
int[] arr=new int[3];
Demo d=new Demo();
int num=d.method(arr,30);
}
}
-
Throws和Throw区别:
1.throws使用在函数上,throw使用在函数内。
2.throws抛出的是异常类,可以抛出多个,用逗号分隔。throw抛出的是异常对象 -
异常处理的捕捉形式:
这是可以对异常进行针对性处理的方式。 -
格式:
try{
//需要被检测异常的代码
}catch(异常类 变量){ //该变量用于接收发生的异常对象
//处理异常的代码
}finally{
//一定会被执行的代码
} -
实现:
class FuShuIndexException extends Exception{
FuShuIndexException(){}
FuShuIndexException(String msg){
super(msg);
}
}
class Demo{
public int method(int[] arr,int index)throws NullPointerException,FuShuIndexException{
if(arr == null)
throw new NullPointerException();
if(index < 0)
throw new FuShuIndexException();
return arr[index];
}
}
class Demo2{
public static void mian(String[] args) {
int[] arr=new int[3];
Demo d=new Demo();
try{
int num=d.method(arr,-30);
}catch(FuShuIndexException f){
//打印标准输出流:异常信息,异常名字,异常位置
e.printStackTrace();
System.out.print("数组角标不能为负!");
}catch(NullPointerException n){
//多个catch
}catch(Exception e){
//父类catch需要放在最后
}
}
}
- 异常处理的原则:
1.函数内容如果抛出需要检测的异常,那么函数上必须声明或者捕捉,否则编译失败。
2.如果调用了声明异常的函数,要么trycatch要么throws,否则编译失败。
3.功能内容可以解决时,用trycatch。解决不了,用throws告诉调用者。
4.如果抛出多个异常就需要捕捉几个异常。 - finally代码块:
class Demo{
public int method(int[] arr,int index)throws ArrayIndexOutOfBoundsException{
if(index > arr.length)
throw new ArrayIndexOutOfBoundsException("数组角标越界"+index);
return arr[index];
}
}
class Demo2{
public static void mian(String[] args) {
int[] arr=new int[3];
Demo d=new Demo();
try{
int num=d.method(arr,30);
}catch(ArrayIndexOutOfBoundsException e){
System.out.print(e);
}finally{
//一定会执行的代码,通常用于关闭(释放)资源
System.out.print("finally");
}
}
}
- 异常的注意事项:
1.子类在覆盖父类方法时,父类的方法如果抛出了异常,那么子类的方法只能抛出父类或者该异常的子类异常。
2.如果父类抛出多个异常,那么子类只能抛出父类异常的子集。
3.如果父类的方法没有抛出异常,那么子类覆盖时绝不能抛,只能try。