The following code uses a boolean preference active
: In the active
state, it does an operation which could throw an exception. On this exception, it does fall back to the non-active
state.
let active = somePreference;
function getValue(parameter) {
try {
if ( active ) {
return valueStore.query(parameter);
} else {
throw {name: 'MyException'};
}
} catch (e) {
return getRandomValue();
}
}
This function can be called several times a second. The valueStore
returns a positive value on success and throws an exception on failure. (as recommended f.ex. by Exception versus return code in DAO pattern).
An alternative would be an external if..else
block to avoid the second exception, but which would have some code duplication.
How to write clean code with an exception and a condition both triggering the same action? In JavaScript, that is.
Related:
- Exception versus return code in DAO pattern says to prefer exceptions to return codes,
- Throwing and catching exceptions in the same function/method throws the wrong kind of exception
- Defensive Programming vs Exception Handling? originally deals with python, and
- https://stackoverflow.com/questions/729379/why-not-use-exceptions-as-regular-flow-of-control once again says that it's okay for Python and stupid for .NET.