1. 为什么需要手动抛出异常对象? 在实际开发中,如果出现不满足具体场景的代码问题,我们就有必要手动抛出一个指定类型的异常对象。 2. 如何理解"自动 vs 手动"抛出异常对象? 过程1:“抛” "自动抛" : 程序在执行的过程当中,一旦出现异常,就会在出现异常的代码处,自动生成对应异常类的对象,并将此对象抛出。 "手动抛" :程序在执行的过程当中,不满足指定条件的情况下,我们主动的使用"throw + 异常类的对象"方式抛出异常对象。 过程2:“抓” 狭义上讲:try-catch的方式捕获异常,并处理。 广义上讲:把“抓”理解为“处理”。则此时对应着异常处理的两种方式:① try-catch-finally ② throws
package chapter09_exception.src.com.atguigu04._throw; /** * ClassName: ThrowTest * Package: chapter09_exception.src.com.atguigu04._throw * Description: * * @Author 小白 * @Create 2024/4/6 14:59 * @Version 1.0 */ public class ThrowTest { public static void main(String[] args) { Student s1 = new Student(); //抛出的是运行时异常 可以不处理 也可以处理 /* try { s1.regist(10); s1.regist(-10); System.out.println(s1.toString()); } catch (RuntimeException e) { //RuntimeException e.printStackTrace(); // System.out.println(e.getMessage()); //输入的id的非法 }*/ //抛出的是编译出异常 这个时候就要选择去处理 try { s1.regist(10); s1.regist(-10); System.out.println(s1.toString()); } catch (Exception e) { //Exception e.printStackTrace(); // System.out.println(e.getMessage()); //输入的id的非法 } } } class Student{ int id; //抛出运行时异常 public void regist(int id ){ if(id >0 ){ this.id = id; }else { //以前 // System.out.println("输入的id的非法"); //现在 //手动抛出异常类的对象 因为抛出的是运行时异常RuntimeException 所以可以选择不处理 // throw new RuntimeException("输入的id的非法"); } } //抛出编译时异常 得处理 得抛出 public void regist1(int id ) throws Exception{ if(id >0 ){ this.id = id; }else { //以前 // System.out.println("输入的id的非法"); //现在 //手动抛出异常类的对象 因为抛出的是运行时异常RuntimeException 所以可以选择不处理 throw new Exception( "输入的id的非法"); } } @Override public String toString() { return "Student{" + "id=" + id + '}'; } }