尽管我的代码返回String,但该函数仍希望返回string

时间:2018-07-14 11:37:44

标签: java

//即使返回成功消息后,我仍然得到预期的String返回值... //任何帮助将不胜感激

public String addStudent(Student student) throws Exception 
{
    try
    {
        Validator validate = new Validator();
        validate.validate(student);
        if((student.getMark1()<50 && student.getMark2()<50 && student.getMark3()<50) && student.getResult()=='P')
            throw new Exception("Service.INVALID_RESULT_PASS");
        if((student.getMark1()>=50 || student.getMark2()>=50 || student.getMark3()>=50) && student.getResult()=='F')
            throw new Exception("Service.INVALID_RESULT_FAIL");
        return "Success";
    }
    catch(Exception e)
    {
        System.out.println(e.getMessage());
    }
}

2 个答案:

答案 0 :(得分:0)

问题是您没有告诉Java如果捕获到Exception时返回什么。您将需要在catch块中或try/catch块之外添加return语句。

话说回来,您是从Exception块中抛出一个新的try/catch,这很奇怪。

如果您想自己抛出这些异常,则这里不需要try/catch

答案 1 :(得分:0)

如果您的意思是您的IDE仍在要求返回,那是因为没有保证代码可以返回某些内容。如果引发异常,它不会返回任何内容,因此请尝试在代码末尾返回一些内容,例如:

function testFunction (frame_count: number, frame_count_correct: number): number {
let score: number = 0 
if (frame_count > 1) {
    score = frame_count_correct/frame_count
} else {
    score = 0
}

return parseInt(score);

(我没有输入所有代码,但是您明白了)