What to return from method if error happens?

The function returns true or false as an answer so if I return any of them, the user might think that it is the answer

if you return true or false you can use it in block (if then) so if it returns true it will execute do and if it is false it will execute else

:sweat_smile:

Try this:

try{
  //your code
  return var;
}catch(Exception e){
  e.printStackTrace();
  return -1; //indicates error
}
return 0; // will never get returned
1 Like

Thanks everybody, I think I will return -1 for int, "error" for String, but what will I return for Boolean?

:+1: :grin:

1 Like

Boolean is true and false

1 Like

But if my function returns them a an answer?
Example:
I created a function to check whether a number is odd. So it will return true or false. But if error occurs and i return false then the user will think that the answer is false.

i don't think it will throw an error, because the error occurs it's possible if you add a string inside the int, so don't worry about that

Also, to clarify, when does an error occur?

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

@Kumaraswamy

Thanks a lot!!!
This is what I was looking for.
It works!

1 Like

I am happy that it helped you. :upside_down_face:

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.