Reputation: 31
I know it's not possibile throw exception and return a value in the same method, but i need to do this in somehow. I was thinking to use finally block to throw the exception and after return the value. Something like:
public Type myMethod() {
try{
//some elaborations
return result;
} catch(MyException myException) {
//do something
return result;
} finally {
if(myException != null) {
throw myException ;
}
}
Is possible something like this, or how can i achieve this?
EDIT: Or can i split in different methods?
Upvotes: 1
Views: 72
Reputation: 6256
"... I know it's not possibile throw exception and return a value in the same method, but i need to do this in somehow. ...
... Is possible something like this ... can i split in different methods?"
The simplest approach would be to use a class.
class Result<T> {
T value;
Throwable e;
}
Here is an example where r will always contain "abc".
Result x() {
Result<String> r = new Result<>();
try {
Integer.parseInt(r.value = "abc");
} catch (Exception e) {
r.e = e;
}
return r;
}
You'll need to check whether e is null.
Result<String> r = x();
if (r.e != null) System.out.println(r.e);
System.out.println("r.value = " + r.value);
Upvotes: 0
Reputation: 1527
Consider creating a custom exception that contains the original Exception as a cause and the current value.
A naive example:
public class ValueException<T> extends Exception {
private T value;
public ValueException(T value, Exception cause) {
super(cause);
this.value = value;
}
... stuff ...
}
Within your method...
public Type myMethod() throws ValueException {
Type result = null;
try {
//some elaborations
return result;
} catch(Exception e) {
throw new ValueException(result, e);
}
}
Some caller...
public Type getType() {
try {
return myMethod();
} catch (ValueException e) {
if (isGoodEnough(e.getValue()) {
return e.getValue();
}
throw new RuntimeException("Failed to get Type", e);
}
Upvotes: 2
Reputation: 6816
Short answer yes. Create a class with 2 data types exception and return value.
public class ReturnExceptionResult {
Object result;
Exception ex;
...
}
public ReturnExceptionResult myMethod() {
Object result;
Exception ex;
try{
//some elaborations
result=returnvalue;
} catch(MyException myException) {
//do something
ex=myException;
result=returnvalue;
}
return new ReturnExceptionResult(result,ex);
}
Upvotes: 0