1

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.

  1. Fetch two numbers from an API, a and b.
  2. 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:

  1. The fetch itself failed.
  2. 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...
}
1
  • You probably want Promises. Commented Oct 14, 2019 at 16:46

3 Answers 3

1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Your if block is sort-of doing try-catch where you either return result or 0. How is it different than using another try-catch? In other words, should we use try-catch only when something out of our control can fail?
Yes, when it's out of your control you can use a try catch block. And use if else to check whether something can / should be executed, don't use try / catch as if / else statement it's a very bad practise!
0

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
  }
}

Comments

0

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...
  }

2 Comments

I do not have an async/await issue here. Assume getFromAPI handles all that. By API errors here, I mean more like a and b are missing (one or both).
if the condition doesn't match you can throw a new error inside try, so that way you won't have to use multiple try-catch

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.