Java异常的处理机制(二)

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 后面加上可能会产生的异常类型)。一旦进行声明,那么这个函数就没有责任来处理这个异常,而是由调用的地方来处理这个异常



原文地址:https://www.cnblogs.com/yjbjingcha/p/6921429.html