Reputation: 2614
I want to query some state and break out of my method on a failure condition but this condition also has to guard against a checked exception.
I'm currently handling it as such:
try {
if (!isSomeState()) {
error("Failed to realize state");
return;
}
}
catch (SomeStateException ex) {
error("Failed to realize state");
return;
}
I could throw the checked exception to drop down into the catch block. But this feels dirty because the exception is just redirecting program flow:
try {
if (!isSomeState())
throw new SomeStateException();
}
catch (SomeStateException ex) {
error("Failed to realize state");
return;
}
It doesn't make sense to have the method throw this exception because I'm meant to handle it in this method as described.
Update:
To clarify, the state being queried utilizes socket i/o and therefore is throwing a extension of IOException
; so the exception itself is not superfluous in this case.
The resulting boolean expresses whether some state is set to true
or false
. It does NOT make sense to return false
on this exception as there will be no point in continuing to query for additional state which could otherwise be valid on false
.
Upvotes: 1
Views: 81
Reputation: 13872
You can use below logic, it is more readable:
boolean flag = false;
try
{
flag = isSomeState();
}
catch(SomeStateException e)
{
// log here too.
flag = false;
}
finally
{
if(!flag)
{
error("Failed to realize state");
return;
}
}
Upvotes: 0
Reputation: 95958
You can modify isSomeState
so that it returns false
instead if throwing an exception. Then all you need to do is simply:
if (!isSomeState()) {
return;
}
Upvotes: 1