tl;dr If a task can fail at multiple events e.g. API fetch, division, parsing etc, does it make sense to have multiple try-catch blocks or a single one to catch 'em all?
I have a function in which I perform two tasks.
- Fetch two numbers from an API,
aandb. - Perform
a/b
This is a simplified version of the actual problem. I wanted to ask how to handle for exceptions as the task can fail on either of the two steps:
- The fetch itself failed.
a/bresulted in an error becauseb = 0.
I can think of two approaches.
Option I
try {
const data = getFromAPI();
const result = data[0] / data[1];
return result;
} catch (err) {
// Catch all errors here...
}
Option II
try {
try {
const data = getFromAPI();
} catch(err) {
// Catch all API errors here..
}
const result = data[0] / data[1];
return result;
} catch (err) {
// Catch division errors here...
}