Pythony
January 23, 2021, 12:20pm
1
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
Pythony
January 23, 2021, 12:25pm
4
But my function is not a void, it returns a value.
Pythony
January 23, 2021, 12:26pm
5
Please explain, I am not able to understand
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;
}
}
Pythony
January 23, 2021, 12:29pm
8
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
Pythony
January 23, 2021, 12:35pm
11
But for methods returning int
?
2 Likes
You cannot return for null Integer.
Pythony
January 23, 2021, 1:04pm
13
If I return -1 for int methods and ""error"" for String methods, then what should I return for boolean methods?
Pythony
January 23, 2021, 1:06pm
14
What do you return in your extensions?
My extensions rarely return (use) integer in SimpleFunction
.