JAVA中的异常

目录

Throwable

Error

Exception

编译时异常

运行时异常

异常的处理

try-catch捕获并处理

finally

throw

throws

自定义异常类


在Java中,将程序执行过程中发生的不正常行为称为异常。
而在JAVA中异常其实是一种类(Exception),JAVA中还有一种类(Error)它被叫做错误。

Throwable

Throwable:是异常体系的顶层类,Error 和 Exception 都是其派生出两个重要的子类

  • Error:指的是Java虚拟机无法解决的严重问题,比如:JVM的内部错误、资源耗尽等,典型代表:StackOverflowError和OutOfMemoryError,一旦发生回力乏术。
  • Exception:异常产生后程序员可以通过代码进行处理,使程序继续执行。

Error

Exception

异常又可以分为:

  • 编译时异常(受查异常)
  • 运行时异常(非受查异常)

编译时异常


程序编译期间发生的异常,称为编译时异常,也称为受检查异常(Checked Exception)。

运行一下代码报出的就是编译时异常。

class Person {

    private String name;
    private String gender;
    int age;
    // 想要让该类支持深拷贝,覆写Object类的clone方法即可
    @Override
    public Person clone() {
        return (Person)super.clone();
    }
}
public class Main{
    public static void main(String[] args) {

    }
}


但是此时需要注意的是并不是代码下面标红就属于编译时异常

例如下面这个就属于语法错误而非异常:

运行时异常


在程序执行期间发生的异常,称为运行时异常,也称为非受检查异常(Unchecked Exception)

    public static void main(String[] args) {
        String a = "234";
        System.out.println(a.charAt(9));
    }

在JAVA中RunTimeException以及其子类对应的异常,都称为运行时异常


异常的处理

try-catch捕获并处理

在JAVA中会使用 try-catch 对异常进行处理。

语法规则:

        try {
            a// 将可能出现异常的代码放在这里
        } catch (要捕获的异常类型 e) {
            b// 如果try中的代码抛出异常了,此处catch捕获时异常类型与try中抛出的异常类型一致时,或者是try中抛出异常的基类时,就会被捕获到
             // 对异常就可以正常处理,处理完成后,跳出try-catch结构,继续执行后序代码
        } catch (要捕获的异常类型 h) {
            c// 如果try中的代码抛出异常了,此处catch捕获时异常类型与try中抛出的异常类型一致时,或者是try中抛出异常的基类时,就会被捕获到
             // 对异常就可以正常处理,处理完成后,跳出try-catch结构,继续执行后序代码
        }

将可能发生异常的代码放入 a 处,如果发生了 e 类型的异常就执行 b 处的代码,如果发生了 h 类型的异常就执行 c 处的代码。

    public static void main(String[] args) {
        try{
            System.out.println(2/0);
            System.out.println("hahah");//因为上一行发生了异常所以本行不会被执行;
        }catch(NullPointerException a){
            System.out.println("处理空指针异常");
        }catch(ArithmeticException a){
            System.out.println("处理算数异常");
        }
        System.out.println("lllllllll");
    }

  • try块内抛出异常位置之后的代码将不会被执行
  • 如果抛出异常类型与catch时异常类型不匹配,即异常不会被成功捕获,也就不会被处理,继续往外抛,直到JVM收到后中断程序----异常是按照类型来捕获的。

finally

有些特定的代码,不论程序是否发生异常,都需要执行,比如程序中打开的资源:网络连接、数据库连接、IO流等,在程序正常或者异常退出时,必须要对资源进进行回收。另外,因为异常会引发程序的跳转,可能导致有些语句执行不到,finally就是用来解决这个问题的。

    public static void main(String[] args) {
        try{
            System.out.println(2/0);
            System.out.println("hahah");//因为上一行发生了异常所以本行不会被执行;
        }catch(NullPointerException a){
            System.out.println("处理空指针异常");
        }catch(ArithmeticException a){
            System.out.println("处理算数异常");
        }finally{
            System.out.println("一定会被执行的语句");
        }
        System.out.println("lllllllll");
    }

就算使用 return 提前退出方法,finally中的语句也会被执行:

    public static void main(String[] args) {
        try{
            return;
        }catch(NullPointerException a){
            System.out.println("处理空指针异常");
        }finally{
            System.out.println("一定会被执行的语句");
        }
        System.out.println("lllllllll");
    }

throw

因为JAVA中的异常本质上是类,所以在JAVA中可以使用 throw 关键字来主动抛出异常。

    public static void main(String[] args) {
        System.out.println("前前前");
        throw new NullPointerException("主动抛出的异常");
        
    }

  • throw必须写在方法体内部
  • 抛出的对象必须是Exception 或者 Exception 的子类对象
  • 如果抛出的是 RunTimeException 或者 RunTimeException 的子类,则可以不用处理,直接交给JVM来处理
  • 如果抛出的是编译时异常,用户必须处理,否则无法通过编译
  • 异常一旦抛出,其后的代码就不会执行

throws

当方法中抛出编译时异常,用户不想处理该异常,此时就可以借助throws将异常抛给方法的调用者来处理。即当前方法不处理异常,提醒方法的调用者处理异常

语法格式:
修饰符 返回值类型 方法名(参数列表) throws 异常类型1,异常类型2...{
}

class Person {

    private String name;
    private String gender;
    int age;
    @Override
    public Person clone() throws CloneNotSupportedException { //在此处使用throws声明异常后就不需要在本段代码中解决此异常了
        return (Person)super.clone();
    }
}
public class Main{
    public static void main(String[] args) {
        Person a = new Person();
        a.clone();//因为此方法使用throws声明了异常,所以就需要调用方来处理该异常
    }
}

  • throws必须跟在方法的参数列表之后
  • 声明的异常必须是 Exception 或者 Exception 的子类
  • 方法内部如果抛出了多个异常,throws之后必须跟多个异常类型,之间用逗号隔开,如果抛出多个异常类型具有父子关系,直接声明父类即可。
  • 调用声明抛出异常的方法时,调用者必须对该异常进行处理,或者继续使用throws抛出

自定义异常类

Java 中虽然已经内置了丰富的异常类, 但是并不能完全表示实际开发中所遇到的一些异常,此时就需要维护符合我们实际情况的异常结构。
因为JAVA中的异常都是继承于 Exception 类,所以我们的自定义异常类也需要继承于 Exception 类。

自定义的登录异常:

import java.util.Scanner;

class NameLogInException extends Exception{
    public NameLogInException(String str){
        super(str);
    }
}

class PasswordLogInException extends Exception{
    public PasswordLogInException(String str){
        super(str);
    }
}

public class Main{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.println("请输入用户名和登录密码:");

        try{
            logIn(in.nextLine(), in.nextLine());
        }catch(NameLogInException a){
            System.out.println("处理用户名异常");
        }catch(PasswordLogInException a){
            System.out.println("处理密码异常");
        }
    }

    public static void logIn(String name, String password) throws NameLogInException, PasswordLogInException{
        if (!name.equals("hello")) {
            throw new NameLogInException("用户名异常");
        }
        if (!password.equals("123456")) {
            throw new PasswordLogInException("密码异常");
        }
    }
}

 

  • 自定义异常通常会继承自 Exception 或者 RuntimeException
  • 继承自 Exception 的异常默认是受查异常
  • 继承自 RuntimeException 的异常默认是非受查异常
  • 34
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 29
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 29
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值