-1

// Even after returning the success message i am still getting String return expected... // Any help will be appreciated

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());
    }
}
Anand
  • 33
  • 1
  • 8

2 Answers2

0

The issue is that you aren't telling Java what to return if an Exception is caught. You will need to add a return statement to your catch block or outside the try/catch block.

That being said, you are throwing a new Exception from within your try/catch block, which is odd.

If you want to throw those Exceptions yourself, then the try/catch is not needed here.

Zephyr
  • 9,885
  • 4
  • 28
  • 63
0

If you mean that your IDE is saying that it still wants a return, its because the code is not guarrenteed to return something. It doesn't return something if an exception is thrown, so try returning something at the end of the code, like:

    catch(Exception e)
    {
        System.out.println(e.getMessage());
    }
    return "";
}

(I haven't typed all the code, but you get the point)

Pieter Mantel
  • 123
  • 1
  • 9
  • Thanks @peter but it will address a null pointer exception if null is returned and if an exception is thrown my program will handle it due to try catch block and if not i'm expected to return "Success" message... – Anand Jul 14 '18 at 11:58
  • @Anand then just `return "Success";` intstead of `return "";` – Pieter Mantel Jul 14 '18 at 12:32