zoukankan      html  css  js  c++  java
  • 异常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;
        }
    }

  • 相关阅读:
    软件构造 第三章第一节 数据类型与类型检查
    类图总结
    【Beta】Scrum07
    【Beta】用户问题反馈及处理(一直更新)
    【Beta】第七次任务发布
    【Beta】Scrum06
    【Beta】第六次任务发布
    【Beta】Scrum5.5
    【Beta】第5.5次任务发布
    【Beta】Scrum05
  • 原文地址:https://www.cnblogs.com/zhujialei123/p/9046730.html
Copyright © 2011-2022 走看看