java-异常

异常

定义:在程序执行过程中,遇到的不正常的现象

error:错误,人为原因产生的,在程序中必须要解决的内容

exception:异常,在程序中可能出现的情况,需要我们人为的避免

  1.运行时异常(运行的时候才能发现)

  2.编译时异常(在编译的时候就有,不处理不能运行)

常见的异常类型

ClassCastException:类型转换异常

NullPointerException:空指针异常

ArrayIndexOutOfBoundsException:数组下标越界异常

ArithmeticException  数学异常

InputMismatchException  输入类型不匹配异常

@Test
 public void test04(){
   //ClassCastException  类型转换异常
//  Object obj = new String("tom");
//  Date date = (Date)obj;
//  System.out.println(date);
   
    //ArrayIndexOutOfBoundsException  数组下标越界异常
//  int [] arr=new int[2];
//  arr[0]=10;
//  arr[1]=11;
//  arr[2]=12;
//  System.out.println(arr[2]);
   
   // NullPointerException  空指针异常
   int [] arr=null;
   System.out.println(arr[1]);

如何使用异常

try   catch   throw   throws  finally

try :  将可能出现异常的代码都放入try中

catch:在一段程序中catch可以有多个,来捕获异常类型,当出现了某种异常就会中断 异常代码后面的内容继而  执行对应的catch中的内容

注意:在使用catch捕获异常的时候,需要将异常的范围从小到大(小范围的放上面,大范围的放下面)

finally: 在程序中一定会被执行的内容,除非是遇到了exit()方法

当程序中有return的时候,是会先执行finally中的内容,然后执行return

throws  Exception: 声明异常

@Test
    public  void test05() {
        TestException e = new TestException();
        try {
            e.show();
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
    
    
    public void  show() throws  Exception{
        
            
        int [] arr =null;
        System.out.println(arr[1]);
    
    }

throw  new  Exception();:​ 抛出异常,我们直接在程序中写异常信息

public void setSex(String sex) {
        /**
         * 如果赋值的是男或者女则正常赋值否则给出异常提示
         */
        if("男".equals(sex) ||  "女".equals(sex)){
            
            this.sex = sex;
        }else{
            //抛出异常
            try {
                throw  new  Exception("性别赋值不正确");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

 

posted @ 2020-05-24 22:09  星点点  阅读(189)  评论(0)    收藏  举报