您的位置:首页 > 编程语言 > Java开发

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

2018-04-02 21:41 603 查看
除了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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: