面试题:有关异常处理中的throw和throws的区别
throw:
- 表示方法内抛出某种异常对象
- 如果异常对象是非 RuntimeException 则需要在方法申明时加上该异常的抛出 即需要加上 throws 语句 或者 在方法体内 try catch 处理该异常,否则编译报错
- 执行到 throw 语句则后面的语句块不再执行
- 测试代码如下:
-
package day16.java; /** * 此代码是在测试“throw” * @author gaoxu * @user ThrowTest1.java * @date 2021年3月17日上午11:10:30 * @description * @return */ public class ThrowTest1 { public static void main(String[] args) { Stu st = new Stu(); st.Regeist(-1002); System.out.println(st.toString()); } } class Stu{ private int id; public void Regeist(int id) { if (id > 0) { this.id = id; } else { //在这种方式下仍然会打印出int型的默认值 System.out.println("输入的学号有误!!!"); //在这种情况下,程序运行停止,不会进行任何的打印操作 throw new RuntimeException("输入的信息有误!!!"); } } @Override public String toString() { return "Stu [id=" + id + "]"; } }
throws:
- 方法向外抛出异常
- 方法的定义上使用 throws 表示这个方法可能抛出某种异常
- 需要由方法的调用者进行异常处理
- 测试代码如下:
-
package day16.java; /** * 此代码是在测试“throws” * @author gaoxu * @user ThrowTest1.java * @date 2021年3月17日上午11:10:30 * @description * @return */ public class ThrowTest1 { public static void main(String[] args) { Stu st = new Stu(); //针对手动抛出Exception异常的捕获 try { st.Regeist(-1002); } catch (Exception e) { System.out.println(e.getMessage()); } System.out.println(st.toString()); } } class Stu{ private int id; public void Regeist(int id) throws Exception { if (id > 0) { this.id = id; } else { //在这种方式下仍然会打印出int型的默认值 System.out.println("输入的学号有误!!!"); //在这种情况下,程序运行停止,不会进行任何的打印操作 //在抛出的类型为Exception时,需要在方法的后面进行异常的抛出“throws Exception”。 //以为Exception包含了:编译异常和输出异常,编译异常不抛出程序没有办法运行 //方法抛出异常后,在调用的时候还需要进行异常的捕获及处理 throw new Exception("信息错误"); } } @Override public String toString() { return "Stu [id=" + id + "]"; } }
错误之处,恳请指正!