1.throw的作用
class Usre {
private int age;
public void setAge (int age) {
if(age < 0) {
RuntimeException e = new RuntimeException ("年龄不能为负数");//生成异常对象
throw e;//抛出
}
this.age = age;
}
}
class Test {
public static void main (String args []) {
User user = new User ();
user.setAge (-20);
}
}
throw的作用就是抛出异常对象
2.throws的作用
class Usre {
private int age;
public void setAge (int age) throws Exception {
if(age < 0) {
Exception e = new Exception ("年龄不能为负数");//生成异常对象
throw e;//抛出
}
this.age = age;
}
}
class Test {
public static void main (String args []) {
User user = new User ();
try{
user.setAge (-20);
}
catch {
System.out.println(e);
}
}
}
throws的作用:在一个函数中有可能会产生异常时,可以选择用try...catch把可能产生异常的代码处理一下,也可以在函数后面声明可能会产生Exception (声明方法:throws 后面加上可能会产生的异常类型),一旦进行声明,那么这个函数就没有责任来处理这个异常,而是由调用的地方来处理这个异常