异常throws与throw的区别

package com.day16.Exception;
/*
* 编译时异常的抛出必须对其进行处理
* 运行时异常的抛出可以处理也可以不处理
* throws 用在方法声明后面,跟的是异常类名
* throw 用在方法体内,跟的是异常对象名
*/

public class ExceptionFive {

  public static void main(String[] args) throws Exception {
    Person p=new Person();
    p.setAge(-17);
    System.out.println(p.getAge());

  }

}
  class Person{
    private String name;
    private int age;
    public Person() {
      super();
    }
    public Person(String name, int age) {
      super();
      this.name=name;
      this.age=age;
    }
    public void setName(String name) {
      this.name=name;
    }
    public String getName() {
      return name;
    }
    public void setAge(int age) throws Exception{
      if(age>0 && age<=150) {
        this.age=age;
      }else {
        throw new Exception("年龄非法");//等价于 Exception e=new Exception("年龄非法"); throw e;
    }
  }
    public int getAge() {
      return age;
    }
}

原文地址:https://www.cnblogs.com/zhujialei123/p/9046730.html