面试题:有关异常处理中的throw和throws的区别

面试题:有关异常处理中的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 + "]";
    	}
    }

    错误之处,恳请指正!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值