【安卓学习笔记】JAVA基础-异常的处理

除了java虚拟机本身能够产生的异常外,经常还会用到自定义异常。
记录下throw和throws的用法。
1.throw
class User{
	private int age;
	
	public void setAge(int age){
		if(age < 0)//在使用User类的时候如果有错误的生成一个异常对象并抛出异常对象
		{
			RuntimeException e = new RuntimeException("the age is error!");
			throw e;//抛出异常对象,虚拟机得到异常对象后将终止代码运行
		}
		this.age = age;
	}
}

class Test{
	public static void main(String args[])
	{
		User user = new User();
		user.setAge(-20);
	}
}
运行结果如下:
Exception in thread "main" java.lang.RuntimeException: the age is error!
        at User.setAge(user.java:7)
        at Test.main(Test.java:5)
2.throws

在使用Exception时这个类将无法编译通过,直接使用Exception,在编译的时候就可能不通过,提示可以对其捕捉或者声明。此时可以使用throws方法:

class User{
	private int age;
	
	public void setAge(int age) throws Exception{
		//throws Exception紧跟在函数后面,代表setAge这个函数有可能会产生Exception异常对象,
		//但是这个对象并不由setAge这个函数来处理,而是由调用这个函数的地方去处理
		if(age < 0)//年龄为负数的时候产生异常对象
		{
			Exception e = new Exception("the age is error!");
			throw e;
		}
		this.age = age;
	}
}
在调用时候使用 try...catch结构
class User{
	private int age;
	
	public void setAge(int age) throws Exception{
		if(age < 0)
		{
			Exception e = new Exception("the age is error!");
			throw e;
		}
		this.age = age;
	}
}
运行结果如下:
java.lang.Exception: the age is error!
By Urien 2018年4月2日 21:41:20


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值