Reputation: 528
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.
a
and b
.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:
a/b
resulted in an error because b = 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...
}
Upvotes: 1
Views: 4708
Reputation: 117
you can simply use:
try {
const data = getFromAPI(); //wait for request to finish
if(typeof data !== 'object') throw('fetch error');
if(data[0] === 0 ||
data[1] === 0 ||
typeof data[0]!== 'number' ||
typeof data[1]!== 'number'
) throw('your error here');
const result = data[0] / data[1];
return result;
} catch (err) {
// Catch all errors here...
}
Upvotes: 0
Reputation: 2337
You should start with checking the data you are working with (as far as reasonably possible). After that you should only try/catch the code which can fail / when it's out of your control, nothing else. So I will give you another option. And to answer your other question, never make nested try catch statements. It simply doesn't make sense. If different type exceptions can occur, try identifying the type of the exception (i.e. with the instanceOf method or properties on the error object) and handle it.
Option III
try {
var data = getFromAPI();
} catch (err) {
// Catch errors from the API request here...
}
if(Array.isArray(data) && !isNaN(data[0]) && !isNaN(data[1]) && data[0] > 0 && data[1] > 0) {
const result = data[0] / data[1];
return result;
}
return 0;
Upvotes: 1
Reputation: 847
This is a question that the answer depends on the system, whether you want to tell the user or want to know what kind of exception was thrown instead of doing several try / catch advise you to use a switch or an if inside the catch instead of multiple nested try / catch.
try{
//your code
}catch(ex){
if(ex instanceof ReferenceError){
//handle error
}
}
Upvotes: 0