异常处理2

来源:互联网 发布:制作推文用什么软件 编辑:程序博客网 时间:2024/04/30 14:17
/*异常处理的方法:声明某个功能可能会出问题:throws Exception,当调用到此函数的时候,要么再声明异常,要么进行处理try{} 放需检测的代码,如果检测到问题,就要生成相关的对象,传给e,catch (Exception e ){  这里写对相关处理代码}声明异常的时候最好把类型精确,可以声明多个异常的类型,但那时catch 处理是也应该多个,如果处理是存在继承,应将最大的放最后*/class FushuException extends Exception{private int value;FushuException(String msg,int value){    super(msg); this.value=value;}public int getValue(){return value;}}class ExceptionDemo {public static void main(String[] args) {        Calculate c=new Calculate();try{  c.div(4,-1);}catch (ArithmeticException e){System.out.println("除零");}catch(ArrayIndexOutOfBoundsException e){System.out.println("数组脚标越界");}catch(FushuException e){System.out.println("负数异常");System.out.println(e.toString());System.out.println(e.getValue());}System.out.println("Over!");}}class Calculate{public void div(int a,int b) throws ArithmeticException,ArrayIndexOutOfBoundsException,FushuException{if(b<0)throw new FushuException("1111",b);int x=a/b;int [] arr=new int [a];System.out.println(arr[4]);System.out.println(x);}}

0 0
原创粉丝点击