手动抛出异常对象

程序在正常执行过程中,一旦出现异常,就会在异常代码处生成一个对应异常类的对象,并将此对象抛出,一旦抛出该对象以后,其后的代码就不再执行。

异常对象的产生方式:
1)系统自动生成的异常对象
2)手动生成异常对象并进行抛出(throw)(注意不是throws,throws是用来处理异常的)

注意: 手动抛异常可以抛Exception及其子类,但一般是抛Exception,RuntimeException或者自定义异常,如果new 其他的异常违背了其他异常的意思

手动抛出异常(要用到throw关键字)的例子:

package test02;

public class StudentTest {
	private int id;
	
	public void setId(int id) {
		if(id>0) {
			this.id=id;
		}else {
			System.out.println("输入数据非法");
		}
	}
	
	@Override
	public String toString() {
		return "StudentTest [id=" + id + "]";
	}

	public static void main(String[] args) {
		StudentTest st=new StudentTest();
		st.setId(-1);
		System.out.println(st);//输入数据非法
							   //StudentTest [id=0]		
	}
}

比如如果输入数据非法,我们想报错而不是像上面那样仍然输出相应的结果,就可以手动抛出异常对象。

package test02;

public class StudentTest {
	private int id;
	
	public void setId(int id) {
		if(id>0) {
			this.id=id;
		}else {
			//System.out.println("输入数据非法");
			//手动抛出异常
			throw new RuntimeException("输入数据非法");
		}
	}
	
	@Override
	public String toString() {
		return "StudentTest [id=" + id + "]";
	}

	public static void main(String[] args) {
		StudentTest st=new StudentTest();
		st.setId(-1);//因为抛出的是运行时异常,所以这里不会报错
		System.out.println(st);
	}

}

RuntimeException有一个构造器是带有形参String message的,注意异常处理中有一个方法叫做 getMessage(),这里就相当于通过构造器对类中的message属性做了赋值。

上面的程序控制台会报异常
如果想要对异常直接进行处理,可以throw Exception

package test02;

public class StudentTest {
	private int id;
	
	public void setId(int id) throws Exception {//注意声明此方法可能会抛出异常
		if(id>0) {
			this.id=id;
		}else {
			//System.out.println("输入数据非法");
			//手动抛出异常
			throw new Exception("输入数据非法");
		}
	}
	
	@Override
	public String toString() {
		return "StudentTest [id=" + id + "]";
	}

	public static void main(String[] args) {
		StudentTest st=new StudentTest();
		try {
			st.setId(-1);
			System.out.println(st);//如果setId()出异常,这条语句不会被执行
		} catch (Exception e) {
			System.out.println(e.getMessage());//输入数据非法
			//注意此时程序就不会输出异常的行数之类的信息了,因为没有用e.printStackTrace();
		}
	}

}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值