java中异常捕获--一篇文章带你弄懂Exception---和自定义异常

18 篇文章 1 订阅

java中异常捕获–Exception—详解


真是应了老罗那句话–少罗嗦,直接看东西


/**
 * @Auther: GavinLim
 * @Date: 2021/7/5 - 07 - 05 - 14:54
 * @Description: PACKAGE_NAME
 * @version: 1.0
 */
public class test {
    public static void main(String[] args) {
        System.out.println("请输入一个数:");
        Scanner scanner = new Scanner(System.in);
       
            int x = scanner.nextInt();
            System.out.println("请输入第二个数");
            int y = scanner.nextInt();
            System.out.println(x/y);
        
        System.out.println("qwewqeqwqwewqwqe");
    }
}

先来看上面的代码,如果我在控制台输入的不是程序要求的,则程序就会报错而终止—如以下操作–
在这里插入图片描述第一个数输入的就不符合要求,后面就没有机会输入第二个数–即后续代码根本不执行;
如果没有学习异常的知识,我们通常会这样处理

if else 来进行处理,但是由于异常可能有很多种,

import java.util.Scanner;

/**
 * @Auther: GavinLim
 * @Date: 2021/7/5 - 07 - 05 - 14:54
 * @Description: PACKAGE_NAME
 * @version: 1.0
 */
public class test {
    public static void main(String[] args) {
        int x = 0;
        int y = 0;

        System.out.println("请输入一个数:");
        Scanner scanner = new Scanner(System.in);
        if (scanner.hasNextInt()) {
            x = scanner.nextInt();
        }
        System.out.println("请输入第二个数");
        if (scanner.hasNextInt()) {
            y= scanner.nextInt();
            if(y!=0){
                System.out.println(x/y);
            }else{
                System.out.println("异常");
            }
        }
        System.out.println("qwewqeqwqwewqwqe");
    }
}

在这里插入图片描述即使用上述方法处理了异常,也未达到想要的效果
所以java’中提供了处理异常的类–
exception

用try catch捕获异常

import java.util.Scanner;

/**
 * @Auther: GavinLim
 * @Date: 2021/7/5 - 07 - 05 - 14:54
 * @Description: PACKAGE_NAME
 * @version: 1.0
 */
public class test {
    public static void main(String[] args) {
        int x = 0;
        int y = 0;
        try {
            System.out.println("请输入一个数:");
            Scanner scanner = new Scanner(System.in);
            if (scanner.hasNextInt()) {
                x = scanner.nextInt();
            }
            System.out.println("请输入第二个数");
            if (scanner.hasNextInt()) {
                y = scanner.nextInt();
                if (y != 0) {
                    System.out.println(x / y);
                } else {
                    System.out.println("异常");
                }
            }
        } catch (Exception e) {

        }
        System.out.println("qwewqeqwqwewqwqe");
    }
}

处理异常的几种方式:
1,干脆不处理
2,捕获异常,但是不处理
3,抛出异常,交由虚拟机处理
4,捕获后将异常抛出

下面分别来看代码—

1,不处理异常–程序中断,后面代码不会执行–(这里指的是qwe…的输出)

在这里插入图片描述

2,捕获异常,但是不处理–处理的话会有相应的提示等;
在这里插入图片描述

public class test {
    public static void main(String[] args)throws  Exception {
        try {
            System.out.println("请输入一个数:");
            Scanner scanner = new Scanner(System.in);
            int x = scanner.nextInt();
            System.out.println("请输入第二个数");
            int y = scanner.nextInt();
            System.out.println(x / y);
        } catch (Exception e) {
            System.out.println("输入错误");
        }
        System.out.println("qwewqeqwqwewqwqe");
    }
}

这里做一个简单的处理—给予提示
在这里插入图片描述

我们可以看到qwe…执行了

3,抛出异常,交由虚拟机处理

public class test {
    public static void main(String[] args)throws  Exception {

            System.out.println("请输入一个数:");
            Scanner scanner = new Scanner(System.in);
            int x = scanner.nextInt();
            System.out.println("请输入第二个数");
            int y = scanner.nextInt();
            System.out.println(x / y);

        System.out.println("qwewqeqwqwewqwqe");
    }
}

在这里插入图片描述

实际上跟第一种很类似,也会中断,只不过在有些代码中会要求你必须处理异常才能运行,所以还是有区别的

4,捕获后将异常抛出

import java.util.Scanner;

/**
 * @Auther: GavinLim
 * @Date: 2021/7/5 - 07 - 05 - 14:54
 * @Description: PACKAGE_NAME
 * @version: 1.0
 */
public class test {
    public static void main(String[] args) throws Exception {
        try {
            System.out.println("请输入一个数:");
            Scanner scanner = new Scanner(System.in);
            int x = scanner.nextInt();
            System.out.println("请输入第二个数");
            int y = scanner.nextInt();
            System.out.println(x / y);
        } catch (Exception e) {
            throw e;
        }


        System.out.println("qwewqeqwqwewqwqe");
    }
}

在这里插入图片描述效果也是程序中断

总结–要想执行后续代码而程序不中断,要捕获异常,最好做一下处理而不是接着把异常抛给上级;
最后说一下finally, 结合try catch’进行使用

finally代码块除了 System.exit(0);能使其不被执行,其他任何情况下都要被执行—

finally代码块主要用于 关闭数据库连接、io 、 socekt资源等的关闭操作;


自定义异常


自定义异常一般很少用,程序提供的一场类基本已经够用了,但还是要学习自定义异常;

在自定义异常之前我们来看一下其他异常类是怎么写的—照葫芦画瓢还不会吗!!!

在这里插入图片描述

以上异常继承自运行时异常,
类里面有—
1,序列化号-----这个先不去管他,后面学到序列化自然会明白,先模仿着写;
2,构造方法(无参的)
3,有参构造.–参数可用于提示信息–(by zero 是不是很熟悉)
4,父类中有很多构造方法,这里只用几个常用的

在这里插入图片描述

模仿开始—

package com.test.except;

/**
 * @author : Gavin
 * @date: 2021/7/5 - 07 - 05 - 20:25
 * @Description: com.test.except
 * @version: 1.0
 */
public class GenderException extends RuntimeException {
    static final long serialVersionUID = -7034939L;
    public GenderException() {
    }

    public GenderException(String message) {
        super(message);
    }
}

总结–自定义异常特点

1,继承异常类
2,写构造方法
3,序列化号(可以不写,如果用不到的话;)

是不是很简单,下面我们用一下这个异常—

package Person;

import com.test.except.GenderException;

/**
 * @author : Gavin
 * @date: 2021/7/5 - 07 - 05 - 20:23
 * @Description: Person
 * @version: 1.0
 */
public class Student {
    String name;
    int age;
    String gender;



    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        if (gender=="男"|gender=="女")
        this.gender = gender;
        else{
       throw new GenderException("性别录入错误");//在这里抛异常
        }
    }

    public Student() {
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                '}';
    }
}

测试类—

package Person;

import com.test.except.GenderException;

/**
 * @author : Gavin
 * @date: 2021/7/5 - 07 - 05 - 20:26
 * @Description: Person
 * @version: 1.0
 */
public class Test {
    public static void main(String[] args) {
        Student per = new Student();
        try {
            per.setGender("未知");
            System.out.println(per.gender);
        } catch (GenderException e) {

            e.printStackTrace();
        }
    }
}

打印异常信息----

Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8
com.test.except.GenderException: 性别录入错误
	at Person.Student.setGender(Student.java:42)
	at Person.Test.main(Test.java:16)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:564)
	at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)

Process finished with exit code 0

我们可以继续测试检查异常类
自定义检查异常类—感兴趣的可以自己试一下;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CodeMartain

祝:生活蒸蒸日上!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值