/*
异常 多catch
*/
class FuShuIndexException extends Exception{
FuShuIndexException(){
}
FuShuIndexException(String msg){
super(msg);
}
}
class Demo{
public int method(int []arr,int index)throws FuShuIndexException,NullPointerException{//这是声明 throws FuShuIndexException
if(arr==null)
throw new NullPointerException("空指针异常");
if(index<0){
throw new FuShuIndexException("数组角标不能为负");
}
return arr[index];
}
}
class ExceptionDemo5{
public static void main(String[] args) {
int [] arr=new int [3];
Demo d=new Demo();
try{
int num=d.method(arr,-1);
System.out.println("num :"+num);
}
catch (NullPointerException e){
System.out.println(e);
}
catch(FuShuIndexException e){//这里要有针对性
System.out.println("message"+e.getMessage());
System.out.println("String"+e);
e.printStackTrace();//jvm默认处理机制就是调用异常对象的这个方法
System.out.println("负数角标异常!!!");
}
catch(Exception e){//多catch 父类的catch放在最下面否则编译失败
//接收其他异常
}
System.out.println("over");
}
}
Java 多catch
最新推荐文章于 2025-05-27 15:54:43 发布