使用throw抛出年龄异常

使用throw抛出年龄异常,第1张

使用throw抛出年龄异常

package Work6;

public class User {
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) throws Exception {
        if(age > 0 && age <= 100) {
            this.age = age;
        }else {
            
            throw new Exception("年龄必须在1到100之间!");
        }
        
    }
    
}

-----------------------------------------------------------------------------------------------------------

package Work6;

import java.util.Scanner;

public class UserDemo {
    
        static Scanner input = new Scanner(System.in); 
        public static void main(String[] args) {
            User user = new User();
            System.out.println("请输入姓名:");
            user.setName(input.next());
            System.out.println("请输入年龄:");
           
            try {
                user.setAge(input.nextInt());
            } catch (Exception e) {
                
                e.printStackTrace();
            }
        }
    }


 

 

 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5637492.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存