Search code examples
javamethodsreturntry-catch

Method return statement vs try-catch


As far as I know in Java errors can be reported in two ways: return values and exceptions.

For example, code below:

int methodName(int i, int j) {
    int result;
    
    try {
        result =  i / j; 
        return result;
        // in the case of j = 0, ArtithmeticException() will be thrown
    }
    catch (Exception e) {
        System.out.println("Some message");
    }
    
    //return result;
}

In the case of j = 0, an exception will be thrown and caught (by the catch), and "Some message" will be printed.

The question is: If I do not want to return any result from this method in the case of a divide by zero, MUST I return some value or there is another way? I.e. using a 'throw' in the catch clause?

And another observation: if I uncomment the last 'return result' statement I get the error message:

variable result might not have been initialized

And if I comment last 'return result' I get the error message:

missing return statement

But I've already included the return statement in the try clause.

Thanks!


Solution

  • In case of j = 0 exception will be thrown and caught (by catch). And message will be printed. The question is: If I do not want to return any result from this method in the case of dividing by zero I still MUST return some value or there is another way? Using 'throw' from catch clause?

    You must either return a value matching the signature (int in this example) or throw something, otherwise the program will not compile.

    And another observation: if I uncomment last return result statement I got an error message: variable result might not have been initialized

    The result variable is assigned in a try block. The compiler doesn't know at which exact point the exception might occur. If an exception occurs before the assignment is completed, then at the point of the return result statement, the variable result might not have a value. The solution is to set a value before the try block.

    And if I comment last 'return result' I got an error message: missing return statement But I've already included return statement in try clause.

    In this example, if an exception occurs in the try block, then the catch block and the rest of the body of the function is executed, and there is no other return statement to match the signature of the method. You must return an int value on all execution paths.