首页 > 解决方案 > 用户定义的异常

问题描述

我对这段代码有一些问题。我收到此错误:: 检查 getCandidateDetails 方法中是否正确抛出异常。尽管测试用例通过了 85%。

候选人.java

public class Candidate {
    
    private String name;
    private String gender;
    private double expectedSalary;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public double getExpectedSalary() {
        return expectedSalary;
    }
    public void setExpectedSalary(double expectedSalary) {
        this.expectedSalary = expectedSalary;
    }
}

主.java

import java.util.*;
public class Main{
    public static void main (String[] args) {
        /* code */
        
    }
       public static Candidate getCandidateDetails() throws InvalidSalaryException{
           try{
           Scanner sc = new Scanner(System.in);
           String name = sc.nextLine();
           String gender = sc.nextLine();
           double expectedSalary = sc.nextDouble();
           if(expectedSalary < 10000){
               throw new InvalidSalaryException("Registration Failed. Salary cannot be less than 10000.");
           }
           Candidate c = new Candidate();
           return c;
           
           }catch(InvalidSalaryException ex){
               return null;
           }
           
       }
}

InvalidSalaryException.java

public class InvalidSalaryException extends Exception{
    public InvalidSalaryException(String str){
        super(str);
    }
}

标签: javaexception

解决方案


我不确定您的问题,但是:

这段代码有一些问题。我收到此错误:: 检查 getCandidateDetails 方法中是否正确抛出异常。尽管测试用例通过了 85%。

如果您的代码这样做(我缩进了它):

public static Candidate getCandidateDetails() throws InvalidSalaryException { // (1)
  try{
    Scanner sc = new Scanner(System.in);
    String name = sc.nextLine();
    String gender = sc.nextLine();
    double expectedSalary = sc.nextDouble();
    if(expectedSalary < 10000){
      throw new InvalidSalaryException("Registration Failed. Salary cannot be less than 10000."); // (2)
    }
    Candidate c = new Candidate();
    return c;
  } catch (InvalidSalaryException ex) { // (3)
    return null;
  }
}

然后

  1. 您是在告诉 Java 该方法可能会抛出一个InvalidSalaryException
  2. 你正在抛出所说的异常。
  3. 您在返回之前捕获了异常null

您不应该捕获异常并将其交给父调用者。

此外,如果您正在对该方法进行单元测试,那么如果使用System.in.


推荐阅读