• Java之Exception


    1,类体系

    通过查看源码和api得知,其中异常,错误的类继承关系图如下

    其中,顶层接口有两个子接口,Error和Exception,如果代码中少了分号或括号,那么运行程序会出错,而异常又分为编译时异常和运行时异常,编译时异常必须处理,不处理无法通过编译,运行时异常经常遇见,空指针异常(NullPointerException),类型转换异常(ClassCastException),数组越界异常(ArrayIndexOutOfBoundsException)等等,

     2,异常的处理

    为了能让程序出现错误依旧可以继续执行下去,因此必须对异常经行处理

    1)JVM默认处理异常的方式

    运行下面代码

    public class ExceptionDemo {
        public static void main(String[] args) {
            System.out.println("stat");
            int a = 100;
            int b = 0;
            System.out.println(a/b);
            System.out.println("over");
        }
    }

    会在控制台打印

     可见,JVM默认处理方式为 

    1,在控制台打印一段数据,

    2,调用System.exit(0)停掉当前程序

    2)处理方式

    那么我们自己该如何处理异常了

    1,try catch 

    try {
                    //catch的参数为异常类型
            } catch (Exception e) {
    
            } finally {
    
            }

    其中fanally会在最后执行,即使程序停止也会执行

    执行流程如下

    public static void main(String[] args) {
            int a =10;
            int b = 0;
            try {
                System.out.println(a/b);
            } catch (ArithmeticException ae){
                System.out.println("出现异常了");
            }
        }

    1,当执行到 a/b 时,系统会抛出ArithmeticException 异常,

    2,程序将catch中的异常和抛出的异常相杜比,如果一致,继续执行,如果不一致,交给JVM处理打印出

    2,throws抛出异常

    public float getResult(int a,int b) throws ArithmeticException{
            return a/b;
        }

    3,自定义异常

    一般继承Exception或者Runnable类,集体代码如下(来自菜鸟教程)

    class WrongInputException extends Exception {  // 自定义的类
        WrongInputException(String s) {
            super(s);
        }
    }
    class Input {
        void method() throws WrongInputException {
            throw new WrongInputException("Wrong input"); // 抛出自定义的类
        }
    }
    class TestInput {
        public static void main(String[] args){
            try {
                new Input().method();
            }
            catch(WrongInputException wie) {
                System.out.println(wie.getMessage());
            }
        } 
    }

    控制台输入  

    "Wrong input"
  • 相关阅读:
    ClassLoader机制:一个类何时会被虚拟机初始化?
    单例模式(含多线程处理)
    代理模式
    Java反射机制深度剖析
    python3.8、3.9安装
    日常随手记
    redux源码阅读之compose,applyMiddleware
    Chrome字体变粗
    JavaScript遍历树结构
    JavaScript 通过队列实现异步流控制
  • 原文地址:https://www.cnblogs.com/hunt1coder/p/12782920.html
Copyright © 2020-2023  润新知