PyStarter PyStarter - 2 months ago 5x
Java Question

In Java, can "throw exception" replace "return" statement? Where should I put the return statement to get a return value?

Java starter, I got 3 questions in below code, :

  1. An error will happen, like"
    Line 18: error: missing return statement", if I didn't put return statement or throw exception at line 16 or line 17, where I annotate.

  2. When I want to get the return value of array result, should I just follows the values where I put into the array in line 11? Why it's not correct if I return at last, such as line 17?

  3. What the usage of line 13 " map.put(nums[i],i); " please?

Thanks for answering!

enter image description here

  1. Not having a return if you are throwing an exception at the last line is fine. I tested it out. But this is no way can be called 'replacing' the return statement. return indicates that the method has finished computation and has reached a result. An 'throw new Exception' indicates that the method encountered a problem with the input, or in the process of the computation. This will let the calling method know that the call was unsuccesful and the calling method can then act on it.

    // No return statement. public Integer example() { if(true) { System.out.println("This is true\n"); } throw new IllegalArgumentException("no such"); }

    1. I have'nt looked into the logic but you should put the return statement immediately after the line where you think the method has completed its job and can now give release the thread to the calling method. If you do want some code to be executed after a return statement which is the case in some use cases. You can use the finally block.

    public Integer example() { try { if (true) { System.out.println("This is true\n"); return 0; } }finally { System.out.println("Always do this\n"); } return 0; }

  2. Map.put - is used to store entries into the map. Always read documentation - map.