Java 异常 try catch

来源:互联网 发布:java变量初始化 编辑:程序博客网 时间:2024/05/29 15:18
/*异常处理的捕捉形式这是可以对异常进行针对性处理的方式具体格式是:try{//需要被检测异常的代码}catch(异常类 变量){//该变量用于接收发生的异常对象(无catch 无处理)//处理异常的代码}//try catch 也可以(不加finally)finally{//一定会被执行的代码}*/class FuShuIndexException extends Exception{FuShuIndexException(){}FuShuIndexException(String msg){super(msg);}}class Demo{public int method(int []arr,int index)throws FuShuIndexException{//这是声明 throws FuShuIndexExceptionif(index<0){throw new FuShuIndexException("数组角标不能为负");}return  arr[index];}}class ExceptionDemo4{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(FuShuIndexException e){//这里要有针对性System.out.println("message"+e.getMessage());System.out.println("String"+e);e.printStackTrace();//jvm默认处理机制就是调用异常对象的这个方法System.out.println("负数角标异常!!!");}System.out.println("over");}}

原创粉丝点击