异常
来源:互联网 发布:厘米换算英尺英寸c语言 编辑:程序博客网 时间:2024/06/05 23:49
异常
class ExceptionDemo {public static void main(String[] args) {Demo d = new Demo();try{int x = d.div(4,0);System.out.println(x);}catch (Exception e){System.out.println("zzz");System.out.println(e.getMessage());//异常信息System.out.println(e.toString());e.printStackTrace();//异常名称 异常信息 异常出现的位置}}}class Demo{int div(int a, int b)throws Exception {return a/b;}}
class ExceptionDemo1 {public static void main(String[] args) {Demo d = new Demo();try{int x = d.div(3,1);System.out.println(x);}catch (ArithmeticException e){System.out.println(e.toString());System.out.println("被零除");}catch(ArrayIndexOutOfBoundsException e){System.out.println(e.toString());System.out.println("角标越界");}}}class Demo{int div(int a, int b)throws ArithmeticException,ArrayIndexOutOfBoundsException {int [] arr = new int[a];System.out.println(arr[4]);return a/b;}}
自定义异常
class Demo{int div(int a, int b)throws FuException {if(b<0)throw new FuException("zzzzz",b);return a/b;}}class FuException extends Exception{private int value;FuException(){}FuException(String msg,int value){super(msg);this.value = value;}public int getValue(){return value;}}class ExceptionDemo2 {public static void main(String[] args) {Demo d = new Demo();try{int x = d.div(4,-1);System.out.println(x);}catch (FuException e){System.out.println(e.toString());System.out.println("错误是:"+e.getValue());}}}
阅读全文