-1

This is more of a good practice question. Many people seem to suggest if the app cannot recover from the error, the try/catch should be at the very top of the stack.

const getSomeData2 = () => {
    //error in this function, not caught
}

const handleSomeData2 = () => {
    try{
        //code that doesn't rely on getSomeData2()
        //...
        //...
        let result = getSomeData2()
        //code that relies on getSomeData2()
    } catch(e) {
        //handle error
    }
}

handleSomeData2()

I see how in this example, it's redundant to execute the code before let result = getSomeData2(). Other than efficiency, is there an other reason why errors must be caught at the top of the stack?

gabe
  • 83
  • 1
  • 8
  • 1
    In a nutshell: you place `try..catch` blocks around pieces of code where you *expect* errors *may* occur, **and you know what to do with errors should you catch one.** You do *not* surround simply anything and everything with `try..catch` just because, since then you probably won't even know what exactly caused the error, and thus probably also won't know what to do with it. _Sometimes_ this is legitimate, but it should not be your default go-to. You also don't `try..catch` just to silence errors, you only do so if you really have a plan B for how to proceed in case of an error. – deceze Aug 10 '23 at 12:20

0 Answers0