java-异常笔记

1.异常的分类,编译时异常,运行时异常

package com.yl.pdfdemo.day06;

import org.junit.Test;

import java.util.Date;
import java.util.Scanner;

/**
 * @Author wfj
 * @Date 2021/4/20
 * @Description 异常
 * @Version 1.0
 */

public class ExceptionTest1 {
        /**
         * 异常体系结构
         * java.lang.Throwable(有两个子类)
         *      ---java.lang.Error:一般不编写针对性的代码进行处理
         *      ---java.lang.Exception:可以进行异常的处理
         *          ---编译时异常(checked)
         *              ---IOException
         *                  ---FileNotFoundException
         *          ---运行时异常(unchecked,RuntimeException)
         *              ---NullPointerException 空指针异常
         *              ---ArrayIndexOutOfBoundsException 数组下标越界异常
         *              ---NumberFormatException 数字转换异常
         *              ---ClassCastException 类型转换异常
         *              ---InputMisMatchException 输入内容不匹配异常
         *              ---ArithmeticException 算术异常
         *              ...........
         */
    //NullPointerException
    @Test
    public void test1() {
        String s1 = "123";
        s1 = null;
        System.out.println(s1.charAt(0));
    }

    //ArrayIndexOutOfBoundsException
    @Test
    public void test2() {
        int[] arr = new int[5];
        System.out.println(arr[5]);
    }

    //ClassCastException
    @Test
    public void test3() {
        Object obj = new Date();
        String str = (String) obj;
    }

    //NumberFormatException
    @Test
    public void test4() {
        String str = "abc";
        int a = Integer.parseInt(str);
    }

    //InputMisMatchException
    @Test
    public void test5() {
        //输入非数字的话,就报异常信息InputMisMatchException
        Scanner scanner = new Scanner(System.in);
        int score = scanner.nextInt();
        System.out.println(score);
    }

    //ArithmeticException
    @Test
    public void test6() {
        int a = 9 / 0;
        System.out.println(a);
    }
}

2.异常处理的方式
1)try-catch-finally

package com.yl.pdfdemo.day06;

import org.junit.Test;

/**
 * @Author wfj
 * @Date 2021/4/20
 * @Description
 * @Version 1.0
 */

public class ExceptionTest2 {
    /**
     * 一、异常的处理,抓抛模型
     *
     * 过程一:抛:程序在正常执行过程中,一旦出现异常,就会在异常代码处生成一个对应异常类的对象
     *              并且将对象抛出,一旦抛出对象以后,其后的代码不再执行
     *             关于异常对象的产生:1)系统自动生成的异常对象
     *                               2)手动生成的一个异常对象,并抛出(trow)
     *
     * 过程二: 抓:可以理解为异常的处理方式:1)try-catch-finally 2)throws
     *
     * 二、try-catch-finally的使用
     *      try {
     *          //可能出现异常的代码
     *
     *      } catch(异常类型1 变量名1) {
     *          处理异常的方式1
     *      } catch(异常类型2 变量名2) {
     *          处理的异常方式2
     *      } catch(异常类型3 变量名3) {
     *          处理异常的方式3
     *      }
     *      ...
     *      finally{
     *          //一定会执行的代码
     *      }
     *
     *      说明:
     *      1.finally是可选的
     *      2.使用try将可能出现异常的代码包装起来,在执行过程中,一旦出现异常,就会生成一个对应异常类的对象,根据此对象的类型
     *      去catch中匹配
     *      3.一旦try中的异常对象匹配到某一个catch时,就进入catch中,进行异常的处理,一旦处理完成,就退出try-catch结构(在没有finally的情况下)
     *      继续执行其后的代码
     *      4.catch中的异常类型如果没有父子关系,则谁声明在上,谁声明在下无所谓
     *        catch中的异常类型如果有父子关系,则子类一定要声明在父类的上面,否则编译时会报错
     *      5.常用的异常对象处理的方式:1)String getMessage() 2)printStackTrace()
     *      6.在try结构中声明的变量出了try后就不能再调用了
     *      7.try-catch-finally结构可以嵌套使用
     *
     *
     */

    @Test
    public void test1() {
        String str = "abc";
        try {
            int i = Integer.parseInt(str);
            //如果上面那行代码出现异常,try{}内以下代码不会再执行
            System.out.println("vue");
        } catch (NumberFormatException e) {
            e.printStackTrace();
            System.out.println("数值转换异常");
        } catch (NullPointerException e) {
            e.printStackTrace();
            System.out.println("空指针异常");
        } catch (Exception e) {
            System.out.println("系统异常");
        }
        System.out.println("java");
    }
}

package com.yl.pdfdemo.day06;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @Author wfj
 * @Date 2021/4/20
 * @Description try-catch-finally的使用
 * @Version 1.0
 */

public class FinallyTest {
    /**
     * 1.finally是可选的
     * 2.finally中声明的是一定会执行的代码,即使catch中又出现了异常,try中有return语句,catch中有return语句等情况
     * 3.像数据连接,输入输出流,网络编程socket,jvm是不能自动回收的,我们需要手动在finally里释放掉
     */

    public static void main(String[] args) {
        FinallyTest t = new FinallyTest();
        int i = t.test();
        System.out.println(i);
    }

    public void test3() {
        FileInputStream inputStream = null;
        try {
            File file = new File("java.txt");
            inputStream = new FileInputStream(file);
            int data = inputStream.read();
            while (data != -1) {
                System.out.print((char)data);
                data = inputStream.read();
            }
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public int test() {
        try {
            int[] arr = new int[10];
            System.out.println(arr[10]);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 2;
        } finally {
            //会在return值之前被执行
            System.out.println("must run...");
            return 3;
        }
    }

    @Test
    public void test1() {
        try {
            int c = 10 / 0;
        } catch (ArithmeticException e) {
          e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //一定会执行
            System.out.println("考虑考虑");
        }
    }
}

2)throws

package com.yl.pdfdemo.day06;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @Author wfj
 * @Date 2021/4/20
 * @Description 异常的处理方式二:throws+异常类型,
 * @Version 1.0
 */

public class ThrowsTest{
    public static void main(String[] args) {
        /**
         * 1."throws+异常类型"写在方法的声明处,指明此方法执行时,可能会抛出的异常
         * 一旦当方法体执行时,出现异常,仍会在异常代码处生成一个异常类对象,此对象满足trows后的异常类型时,就会抛出
         * 异常代码的后续代码就不再执行
         *
         * 2.体会:try-catch-finally:真正地将异常给处理掉了
         *          throws的方式只是将异常抛给了方法的调用者,并没有真正将异常处理掉
         *
         * 3.开发中选谁?
         *  1)如果父类中的被重写的方法没有throws方式处理异常,那么子类重写的方法也不能使用throws,意味着,如果子类重写的方法
         *  有异常,必须使用try-catch-finally
         *  2)执行的方法a中,其内部又调用了b,c,d,e这四个方法,这时候,最好的是,这四个方法用throws的方式,然后a方法用try-catch-finally
         *
         * 面试题:
         *      throw 和 throws区别
         *      throw: 表示抛出一个异常类对象,生成异常类对象的过程,声明在方法体内
         *      throws: 属于异常处理的一种方式,声明在方法的声明处
         *
         */
        method3();
    }
    public static void method3() {
        try {
            method2();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void method2() throws IOException{
        method1();
    }

    public static void method1() throws FileNotFoundException,IOException{
        File file = new File("java.txt");
        FileInputStream inputStream = new FileInputStream(file);
        int data = inputStream.read();
        while (data != -1) {
            System.out.print((char)data);
            data = inputStream.read();
        }
        inputStream.close();

    }
}

3.练习
1)

package com.yl.pdfdemo.day06;

/**
 * @Author wfj
 * @Date 2021/4/20
 * @Description
 * @Version 1.0
 */

public class EcDef extends Exception {
    static final long serialVersionUID = -3387516993124229948L;

    public EcDef() {

    }
    public EcDef(String msg) {
        super(msg);
    }
}

package com.yl.pdfdemo.day06;

/**
 * @Author wfj
 * @Date 2021/4/20
 * @Description 异常练习
 * @Version 1.0
 */

public class EcmDef {
    public static void main(String[] args) {
        try {
            int i = Integer.parseInt(args[0]);
            int j = Integer.parseInt(args[1]);
            int result = ecm(i,j);
            System.out.println(result);
        } catch (NumberFormatException e) {
            System.out.println("数据类型不一致");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("数组下标越界异常");
        } catch (ArithmeticException e) {
            System.out.println("除0");
        } catch (EcDef ecDef) {
            System.out.println(ecDef.getMessage());
        }
    }

    public static int ecm(int i, int j) throws EcDef{
        if (i < 0 || j <0) {
            throw new EcDef("分子或者分母不能为负数");
        }
        return  i / j ;
    }
}

2)自定义异常

package com.yl.pdfdemo.day06;

/**
 * @Author wfj
 * @Date 2021/4/20
 * @Description 自定义异常,继承于现有的异常结构:RuntimeException(),Exception()
 * @Version 1.0
 */

public class MyException extends RuntimeException{
    static final long serialVersionUID = -7034897190745766939L;

    public MyException() {

    }

    public MyException(String msg) {
        super(msg);
    }
}

3)

package com.yl.pdfdemo.day06;

import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @Author wfj
 * @Date 2021/4/20
 * @Description 方法的重写规则之一:子类重写的方法抛出的异常类型不能大于父类方法抛出的异常
 * @Version 1.0
 */

public class OverrideTest {
    public static void main(String[] args) {
        OverrideTest test = new OverrideTest();
        test.show(new SubClass());
    }
    public void show(SuperClass s) {
        try {
            s.method();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

class SuperClass{
public void method() throws IOException{

}
}
class SubClass extends SuperClass{
    public void method() throws FileNotFoundException{

    }
}

4)

package com.yl.pdfdemo.day06;

/**
 * @Author wfj
 * @Date 2021/4/20
 * @Description 异常练习
 * @Version 1.0
 */

public class ReturnExceptionDemo {
    public static void main(String[] args) {
        //methodA
        //methodA finally
        //methodA runtimeException
        try {
            methodA();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        //methodB
        //methodB finally
//        methodB();
    }

    static void methodA() {
        try {
            System.out.println("methodA");
            throw new RuntimeException("methodA runtimeException");
        } finally {
            System.out.println("methodA finally");
        }
    }

    static void methodB() {
        try {
            System.out.println("methodB");
            return;
        } finally {
            System.out.println("methodB finally");
        }
    }
}
结果
methodA
methodA finally
methodA runtimeException

5)

package com.yl.pdfdemo.day06;

/**
 * @Author wfj
 * @Date 2021/4/20
 * @Description 手动抛出异常
 * @Version 1.0
 */

public class StudentTest {
    public static void main(String[] args) {
        Student student = new Student();
        student.regist(-100);
    }
}
class Student {
    private int id;
    public void regist(int id) {
        if (id > 0) {
            this.id = id;
        } else {
            //手动抛出异常
            throw new RuntimeException("输入的数据非法");
        }
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                '}';
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值