• java_基础_异常


    之前只是了解的最基础的异常形式,没有过多的深入

    今天因为一些原因了解了一下

    下面来说说异常的几种形式

    1.try-catch语句块

    代码示例

    class test{
        public static void main(String[] args) {
            try {
                int a = 1/0;
                System.out.println(a);
            }catch(ArithmeticException e) {
                e.printStackTrace();
                System.out.println(e);
            }finally{
    //final语句块中最后都会执行(不管有没有异常)
        } } }

    因为分母不能为零,所以此处会报出一个算术异常,这就是try-catch语句块基本形式了

    2.抛出异常

    代码示例:

    class test{
        public static void main(String[] args) throws ArithmeticException{
                int a = 1/0;
                System.out.println(a);
        }
    }

    此处是将异常抛出了,通俗来讲,就是把异常丢给了上一级,由上一级来处理

    3.语句中某种条件下抛出异常

    代码示例:

    class test{
        public static void main(String[] args) {
            try {
                int a = 1;
                int b = 0;
                if(b==0)throw new ArithmeticException("the denominator connot be zero");
                System.out.println(a);
            }catch(ArithmeticException e) {
                e.printStackTrace();
                System.out.println(e);
                System.out.println(e.getMessage());
            }
        }
    }

    此处,是在判断分母为零之后手动抛出的异常,这种异常可以自定义一句抛出的时候的语句,在catch语句中利用e.getMessage()方法可以获取自定义的语句,直接输出e对象,就是输出异常加上自定义语句,如上示例代码输出的是

    java.lang.ArithmeticException: the denominator connot be zero
        at Excertion.Test.main(Test.java:12)
    java.lang.ArithmeticException: the denominator connot be zero
    the denominator connot be zero

    这种方法更灵活

    4.自定义异常

    这种方法就是创建一个异常类,此类必须集成Exception父类,类中可以没有东西,也可以重写父类方法

    示例代码:

    class MyException extends Exception{
        private String message = "";
        
        MyException(String str){
            this.message+=str;
        }
        @Override
        public String getMessage() {
            // TODO 自动生成的方法存根
            return this.message;
        }
        
    }
    
    class test{
        public static void main(String[] args) {
            try {
                int a = 1;
                int b = 0;
                if(b==0)throw new MyException("the denominator connot be zero");
                System.out.println(a);
            }catch(MyException e) {
                System.out.println(e);
            }
        }
    }

    详细如上代码,此不再赘述

    注:在try-catch语句块中错误出错代码或者手动抛出异常代码之后的语句不会被执行,但是在try-catch语句块之外之后的语句块会被执行

    希望对大家有所帮助

    以上

  • 相关阅读:
    连接APB1和APB2的设备有哪些
    STM32串口配置步骤
    gcc -o test test.c编译报错
    EmBitz1.11中将左边的目录弄出来
    c51
    c51跑马灯
    51 单片机 跑马灯2
    51 单片机 跑马灯
    spring注解注入:<context:component-scan>以及其中的context:include-filter>和 <context:exclude-filter>的是干什么的?
    Cookie和Session的作用和工作原理
  • 原文地址:https://www.cnblogs.com/lavender-pansy/p/10776391.html
Copyright © 2020-2023  润新知