What to return from method if error happens?

Hello, I found this method, and it works:

So here we are returning object insted of fixed type like boolean or it. Object can be anything. Here we will do a test, here we are dividing a and b and return the result (integer). As you know in java when you try to divide something by 0, you get the error so we return false.

@SimpleFunction
    public Object Something(int a, int b) {
        try {
            return a / b; // WILL RETURN RESULT IF IT WAS SUCCESSFUL
        } catch (Exception e) {
            e.printStackTrace(); // WILL THROW ERROR
            return false; //  SO IT RETURNS FALSE
        }
    }

Test:

So in the first block we are dividing 43 by 7 for test. The result is 6 as the values provided are valid. As in the 2nd block you get false because second param or the num (b) is 0 and it gives error and we return false.

Another test:

Here we take 3 parms, we divide int 'a' by 'b' and check if the answer is the 'result' which returns boolean. If error occurs we return -1

 @SimpleFunction
    public Object Calculate(int a, int b, int result) {
        try {
            return a / b == result;
        } catch (Exception e) {
            return -1;
        }
    }

Result:

In the first block we check if 4 / 7 equals 0.57143. As it's true it returns true. In the second block we see the result is 88 which is false and we return false... In the third block we here also try to divide by 0 so error occurs and return -1 which means like error.

I think this is what you're looking for,
I am sure this is the only best way to do in just one block.
Users can check using the condition block if it's error, or the result.

1 Like