异常
1 /** 2 * 异常:分为编译时异常与运行时异常,其中运行时异常不需要去处理RuntimeException 3 * 1:编译时异常有,空指针,数组角标越界,数据转换,算数异常等等 4 * 2:使用try讲可能异常的代码包装起来,在执行过程中,一旦出现异常就会生成一个异常类的对象,根据此对象的类型, 5 * 去catch中匹配 6 * 3:一旦try中的异常对象匹配到某一个catch时,就进入进行异常处理,处理结束后就跳出来 7 * 4:catch中的异常类型如果有子父类关系,子类声明在上面 8 * 5:常用的处理异常对象的方法:1:String getMessage() 2:printStackTrace() 9 * 6:在try中声明的变量,出了try结构后不可以被调用,可以在try结构体外声明,在里面赋值 10 * 7:try-catch-finally:真正的将异常处理掉了,throws只是将异常抛给了方法的调用者,最后还是要try来解决 11 * 8:两种方式该怎么样选择? 12 * 8.1:如果父类中被重写的方法没有被throws抛出,则子类重写的方法也不能使用,必须使用try处理 13 * 8.2:执行的方法A中,先后调用了其他方法,这几个方法时按照递进方式执行的,我们建议将这个几个方法进行throws处理 14 * 而被执行的方法A中可以考虑使用try进行处理 15 * 9:还可以手动的throw一个异常类的对象 16 * 17 */ 18 19 public class Demo3 { 20 public static void main(String[] args) { 21 22 Demo3 demo3=new Demo3(); 23 try { 24 demo3.ExceptionTest(-1); 25 } catch ( Exception e) { 26 System.out.println(e.getMessage()); 27 } 28 } 29 30 public void sum(){ 31 int n; 32 n = add(); 33 System.out.println(n); 34 } 35 int[]arr=new int[10]; 36 public int add() {//对于有返回值的方法,try和catch,finally结束都要return返回值 37 //int[]arr=new int[10]; 38 try { 39 System.out.println(arr[10]); 40 System.out.println(123); 41 return 1; 42 43 } catch (ArrayIndexOutOfBoundsException e) { 44 e.printStackTrace(); 45 return 2; 46 } finally { 47 System.out.println("一定会执行"); 48 return 3; 49 } 50 } 51 52 public void ExceptionTest(int age) throws Exception{//单元测试方法不可以有形参,且必须是public修饰 53 if (age>0){ 54 System.out.println(123); 55 }else { 56 //throw new RuntimeException("您输入的数据错误");//手动生成异常对象 57 throw new Exception("您输入的数据错误");//如果改成编译时异常, 58 // 可以通过方法后面加上throws抛出异常来解决,抛出到main方法中必须要进行解决,解决方法为try-catch。。 59 } 60 } 61 }
1 public class Demo2 { 2 public static void main(String[] args) { 3 try { 4 int i=Integer.parseInt(args[0]); 5 int j=Integer.parseInt(args[1]); 6 int result=ecm(i,j); 7 System.out.println(result);} 8 catch (NumberFormatException e){ 9 System.out.println("数据类型不一致"); 10 }catch (ArrayIndexOutOfBoundsException e){ 11 System.out.println("缺少命令行参数"); 12 }catch (ArithmeticException e){ 13 System.out.println("除0"); 14 }catch (EcDef e){ 15 System.out.println(e.getMessage()); 16 } 17 18 19 } 20 public static int ecm(int i,int j) throws EcDef{ 21 if (i< 0 || j <0){ 22 throw new EcDef("分子或者分母为负数"); 23 } 24 return i/j; 25 } 26 }
创建异常类
1 //手动定义异常类 2 public class EcDef extends Exception{ 3 static final long VersionUID=-34451299621L;//1:创建版本号 4 public EcDef(){//2:创建空参构造器 5 } 6 public EcDef(String msg){//创建带参构造器,调用super方法 7 super(msg); 8 } 9 }