【问题标题】:how to use try and catch block to generate an custom exception?如何使用 try 和 catch 块来生成自定义异常?
【发布时间】:2022-12-11 20:33:32
【问题描述】:

y 如果用户 ID 为负,我需要生成异常。我试过了,但没有得到任何相关的结果文本

public void registerUser() {
        System.out.println("Please Enter your userId : ");
        int userId = sc.nextInt();
        boolean flag = true;
        for(User userdetails : listUsers) {
            if(userdetails.getUserId() == userId) {
                System.out.println("The deatils which you entered User is already present.pLease Login..");
                flag = false;
                break;
            }
        }
        
        if(flag) {
            System.out.println("Please Enter userName : ");
            String username = sc.next();
            System.out.println("Please enter your emailId : ");
            String emailId = sc.next();
            System.out.println("Enter your password : ");
            String password = sc.next();

            listUsers.add(new User(userId,username,emailId,password));
            System.out.println("user details added successfully..!");
        }
        

【问题讨论】:

    标签: exception try-catch


    【解决方案1】:

    要在 Java 中抛出异常,您可以这样做:

    throw new Exception("Exception message");
    

    所以我想你想这样做:

    if (userId < 0) {
       throw new Exception("UserId is negative");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-05
      • 2021-09-08
      • 2015-10-31
      • 2020-12-02
      • 2016-10-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      相关资源
      最近更新 更多