What to return from method if error happens?

I have a method that has a return type of int and I have used try-catch to handle errors. When I run it, it throws an error that a return statement is missing. So what should I return from the method if an error happens?

I am not able to return null as it needs a function wrapper and not a primitive type.

Yes you cannot return null. The thing you can do is, if the error occurs you can just return like -1 or 0. Else you can directly put return statement at the end and in try-catch also. Then no need to return in exception.

MY Example :

@SimpleFunction(description = "")
public void SetGradientBackground(AndroidViewComponent component, Object orientation, int color1, int color2) {
    try {
     // add your code here
    } catch(Exception e) {
      //  ErrorOccured(e.getMessage());
      ErrorOccured("Error Woohoo");

    }  

@SimpleEvent(description = "")
public void ErrorOccured(String error) {
    EventDispatcher.dispatchEvent(this, "ErrorOccured", error);
}

this code will return the message = Error WooHoo

But my function is not a void, it returns a value.

Please explain, I am not able to understand

yeah it's okay

You could do like this:

@SimpleFunction
    public int Something(int a , int b) {
        try {
            return a + b;
        } catch (Exception e) {
            // TODO HANDLE ERROR
        }
        return -1;
    }

Or like this:

@SimpleFunction
    public int Something(int a , int b) {
        try {
            return a + b;
        } catch (Exception e) {
//       ERROR OCCURED!
            return -1;
        }
    }

Isn't there any other alternative other than returning -1 as if I want the method to return -1 as the answer so the users may get confused

The simple explanation to this is because you only return value if it was successful. In the case of error you do not return anything.

All you can do is, use event blocks, in case of success you call the event block or catch/throw an error.

how about return this, may you like it :

return "null";

or

return "error";

returns as a string

1 Like

But for methods returning int?

2 Likes

You cannot return for null Integer.

If I return -1 for int methods and ""error"" for String methods, then what should I return for boolean methods?

What do you return in your extensions?

My extensions rarely return (use) integer in SimpleFunction.

So you use void methods?

What about this?

Simple Way :
return 0;

For boolean?

return true;

or

return false;