JAVA 抛出异常throw

概述

throw 关键字用来 拋出一个异常

什么时候抛出异常

在编写程序时,我们必须要考虑程序出现问题的情况。

比如,在定义方法时,方法需要接受参数。那么,当调用方法使用接受到的参数时,首先需要先对参数数据进行合法的判断,数据若不合法,就应该告诉调用者,传递合法的数据进来。这时需要使用抛出异常的方式来告诉调用者。

格式

throw new 异常类(参数);
  • 异常类 必须是 Exception 类 或 其子类。
  • 如果是 自定义异常类,也必须是 Exception 的 直接 或 间接 子类。

例如,以下语句在编译时将会产生语法错误:

throw new String("拋出异常");    // 因为String类不是Throwable类的子类

注意

当 throw 语句执行时,它后面的语句将不执行,此时程序转向调用者程序

例子

年龄设置错误时,抛出运行时异常:

public class Student {
    private String name;
    private int age;

    public String getName(){
        return this.name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if(age<0 || 180<age){//保护作用,过大过小都会提示
//            System.out.println("年龄设置错误!");
//            return;//不在继续往下执行,跳出方法继续执行
//          是程序员犯的错误,所以应该抛运行时异常
            throw new RuntimeException("年龄设置错误!");
        }
        this.age = age;
    }

}

测试:

public class Test {
    public static void main(String[] args) {
        Student lilei=new Student();
        lilei.setName("李雷");
        //不知道传递参数发生错误
        //是程序员犯的错误,所以应该抛运行时异常
        lilei.setAge(-20);

    }
}