简体   繁体   中英

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? Ie 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!

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.

What you want to achieve can be achieved by below sample code

As ArithmeticException is RuntimeException and in case of j=0 exception will be propagated to caller function.

int methodName(int i, int j) {
                    return i/j;
               }

Maybe something like this:

  static int methodName(int i, int j) {
    if (j == 0) throw new ArithmeticException();
    return i/j;
  }

You could also use Integer type for result and initialize it to null and your code would compile:

Integer result = null;

Either way, the calling code will need to handle the exception or the possible null value.

One thing that you are probably observing is the scope of the variable.

When one wants to call a void method so that its return ing nothing ; yet, still have it changing the values of a variable, one can put the variable they want changed in the global scope.

An example of how this looks is demo below:

public class MyClassName{
    //global scope int
    public static int result;
    //main method
    public static void main(String[] args){
        //Let's see what we start at
        System.out.println("By default im at: " + result);
        //Attempt to set global variable as the result of a 0 division
        methodName(1,0);
        System.out.println("I tried to divide by zero but I'm still at: "+result);
        //Attempt to perform normal calculation 25/5
        methodName(25, 5);
        System.out.println("25 divided by 5 is: "+result);
    }
    //method that changes global variable - void means it returns nothing
    public static void methodName(int i, int j) {
            try {
                //try 1 / 0
                result =  i / j; 
            }
            catch (Exception e) {
                System.out.println("CATCH:I failed to divide by zero.");
            }
        }
}

Output:

By default im at: 0
CATCH:I failed to divide by zero.
I tried to divide by zero but I'm still at: 0
25 divided by 5 is: 5

Please note the positioning of the global variable, outside the main method. In this example, the value of the variable result is still changed, but is not necessarily return ed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM