• Java异常


    1.异常引入

    package exception;
    @SuppressWarnings({"all"})
    /**
     * @Author Blueshadow
     * @Date 2021/7/30 11:01
     * @Version 1.0
     */
    public class exception {
        public static void main(String[] args) {
            //通过try...catch...异常处理机制来处理异常,从而保证程序的健壮性
            int a = 10;
            int b = 0;
            int num = 0;
            try {
                num = a / b;//尝试执行
            } catch (Exception e) {//捕获错误
                System.out.println("异常信息是"+e.getMessage());
            }
            System.out.println("程序继续执行");
            System.out.println("num="+num);//程序抛出ArithmeticException异常,程序结束执行
    
        }
    }
    
    

    2.异常介绍

    • 为基本概念:Java语言中,将程序执行中发生的不正常现象称为异常,语法错误和逻辑错误不是异常。
    • 异常的分类:
      • Error:Java虚拟机无法解决的严重问题。如:JVM系统内部错误、资源耗尽等严重情况。比如:栈溢出。Error错误是严重错误,程序会崩溃。
      • Exception:其他原因编程错误或偶然的外在因素导致的一般性问题,可以通过针对性的代码进行处理。例如空指针访问,试图读取不存在的文件,网络连接中断等,Exception分为两大类,运行时异常和编译时异常。

    3.异常体系

    4.五大运行时异常(RuntimeException)

    4.1NullPointException空指针异常

    当程序试图在需要对象的地方使用null时,抛出该异常。

    package exception;
    @SuppressWarnings({"all"})
    /**
     * @Author Blueshadow
     * @Date 2021/7/30 11:01
     * @Version 1.0
     */
    public class exception {
        public static void main(String[] args) {
            String name = null;
            System.out.println(name.length());
            //Exception in thread "main" java.lang.NullPointerException
        }
    }
    
    

    4.2ArithmeticException数学运算异常

    当出现异常的运算条件的时候,抛出该异常。

    package exception;
    @SuppressWarnings({"all"})
    /**
     * @Author Blueshadow
     * @Date 2021/7/30 11:01
     * @Version 1.0
     */
    public class exception {
        public static void main(String[] args) {
            int a = 10;
            int b = 0;
            int count = a/b;
            System.out.println(count);
            //Exception in thread "main" java.lang.ArithmeticException: / by zero
        }
    }
    
    

    4.3ArrayIndexOutOfBoundsException 数组下标越界异常

    用非法索引访问数组时抛出的异常。

    package exception;
    @SuppressWarnings({"all"})
    /**
     * @Author Blueshadow
     * @Date 2021/7/30 11:01
     * @Version 1.0
     */
    public class exception {
        public static void main(String[] args) {
            int[] a = {1,2,3,4,5};
            for (int i = 0; i <= a.length; i++) {
                System.out.println(a[i]);
                //Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
            }
        }
    }
    
    

    4.4ClassCastException类型转换异常

    当试图将对象强制转换为不是实例的子类时,抛出该异常。

    package exception;
    @SuppressWarnings({"all"})
    /**
     * @Author Blueshadow
     * @Date 2021/7/30 11:01
     * @Version 1.0
     */
    public class exception {
        public static void main(String[] args) {
            A b = new B();//向下转型
            B b1 = (B)b;//向下转型
    
            C c2 = (C)b;
            //Exception in thread "main" java.lang.ClassCastException: exception.B cannot be cast to exception.C
        }
    }
    
    class A{}
    class B extends A{}
    class C extends A{}
    

    4.5NumberFormatException数字格式不正确异常

    当程序试图将字符串转换成一种数值类型,但该字符串不能转换为适当格式时,抛出该异常。

    package exception;
    @SuppressWarnings({"all"})
    /**
     * @Author Blueshadow
     * @Date 2021/7/30 11:01
     * @Version 1.0
     */
    public class exception {
        public static void main(String[] args) {
            String str = "Hello world";
            int num = Integer.parseInt(str);
            //Exception in thread "main" java.lang.NumberFormatException: For input string: "Hello world"
        }
    }
    
    

    5.常见编译异常

    编译异常是指在编译代码期间就必须进行处理的异常,否则代码不能通过编译

    常见的编译异常

    SQLException//操作数据库时,查询表可能发生异常
    
    IOException//操作文件时发生的异常
    
    FileNotFoundException//当操作文件,而文件不存在时,发生异常
    
    ClassNotFoundException//加载类,而该类不存在时,发生异常
    
    EOFException//操作文件,到文件末尾,发生异常
    
    IIIegalArguementException//参数异常
    

    6.异常处理机制

    6.1处理方式

    try-catch-finally//在代码中捕获发生的异常,自行处理
    
    throws//将发生的异常抛出,交给调用者(方法)来处理,最顶级的处理者就是JVM
    

    6.2try-catch-finally

    try{
        //代码/可能有异常
    }catch{
        //捕获到异常
        //当异常发生时
        //当系统将异常封装成Exception对象e,传递给catch
        //得到异常对象后自行处理
    }finally{
        //不论是否有异常,一定会执行的代码块
    }
    

    6.3throws异常处理

    如果一个方法中可能生成某种异常,但并不能确定如何处理这种异常,则此方法应显示声明抛出异常,表明该方法不对这些异常进行处理,而由该方法的调用者进行处理。

    在方法声明中用throws语句可以声明抛出异常的列表,throws后面的异常类型可以是方法中产生的异常类型,也可以是它的父类。

    6.4自定义异常

    当程序中出现了错误,但是该错误信息并没有在Throwable子类中描述处理,则这个时候可以自己设计异常类,用于描述该错误信息。

    package exception;
    @SuppressWarnings({"all"})
    /**
     * @Author Blueshadow
     * @Date 2021/7/30 11:01
     * @Version 1.0
     *
     * 案例:在接收Person对象的年龄的时候,要求是在18-120岁之间,否则抛出一个自定义异常,
     * 该自定义异常继承RuntimeException
     */
    public class exception {
        public static void main(String[] args) {
         int age = 800;
         if (!(age>=18 && age<=120)){
             //通过构造器输入异常信息
             throw new AgeException("年龄必须在18-120之间");
         }
         //Exception in thread "main" exception.AgeException: 年龄必须在18-120之间
            System.out.println("你的年龄范围正确");
        }
    }
    //自定义异常
    class AgeException extends RuntimeException{
        public AgeException(String message) {//构造器
            super(message);
        }
    }
    
    //一般情况下自定义异常要继承RuntimeException,即定义成运行时异常,好处是我们可以使用默认的处理机制
    

    6.5throw和throws的区别

    意义 位置 后面跟的东西
    throws 异常处理的一种方式 方法声明处 异常类型
    throw 手动生成异常对象的关键字 方法体中 异常对象
  • 相关阅读:
    [跟我学spring学习笔记][更多DI知识]
    [跟我学spring][Bean的作用域]
    [跟我学spring学习笔记][DI循环依赖]
    [跟我学spring学习笔记][IoC]
    [跟我学Spring学习笔记][DI配置与使用]
    [Spring入门学习笔记][静态资源]
    [Spring入门学习笔记][Spring的AOP原理]
    介绍map.entry接口
    hashmap的遍历方法
    java中的队列
  • 原文地址:https://www.cnblogs.com/nanfengashuai/p/15080500.html
Copyright © 2020-2023  润新知