Handle failures where recovery is meaningful
throw reports an exceptional failure. try/catch handles exceptions from work performed within its protected synchronous execution or awaited promise continuation. finally runs for cleanup, but a return or throw there can override an earlier result.
class InvalidScoreError extends Error {
constructor(message) {
super(message);
this.name = 'InvalidScoreError';
}
}
function requireScore(value) {
if (!Number.isFinite(value) || value < 0 || value > 100) {
throw new InvalidScoreError('Score must be from 0 to 100');
}
return value;
}
try {
console.log(requireScore(120));
} catch (error) {
if (error instanceof InvalidScoreError) console.log(error.message);
else throw error;
} finally {
console.log('Validation attempt finished');
}Expect the score message followed by the cleanup message. Unknown failures are rethrown rather than hidden. Throw Error objects with useful messages instead of arbitrary strings when designing an application error contract.
Do not convert failure into plausible data
Returning zero after every failed score read makes a network failure indistinguishable from a real zero. Use a documented result shape or throw an error the caller can handle. Show users a useful action and keep internal details in appropriate safe logs.
Async boundary
A try around setTimeout registration cannot catch a throw in that callback later. Use handling inside the callback or a promise/async flow whose rejection is actually awaited. Calling an async operation without handling its promise leaves a separate failure path.
Cleanup discipline
Use finally to restore pending UI or release a resource. Do not return a success message from finally, because that can suppress an exception. In a catch, distinguish expected validation failures from programming defects instead of swallowing everything.
Practice
- Test valid zero, valid 100, -1 and NaN.
- Introduce an unrelated ReferenceError and confirm the handler rethrows it.
- Wrap an awaited rejected promise and observe catch handling.
- Remove a return from finally in a test example and compare how it changes the function's outcome.