Skip to content
Advertisement

Catch block does not execute immediately after exception is thrown in try block

I have a bit of Javascript code, which is not behaving as I’d expect it to. Can someone tell me what is going on here?

Here’s a simplified version:

JavaScript

The parser() here is an async function, but it also calls some callbacks passed to it (I’m only showing one here, but there are multiple). It calls the rowCb() callback for each row in a file.

It’s the try/catch block within the async callback which is not behaving as I’d expect. I’m using a test file, with three rows, which will cause every call to processRow() to throw an exception. So, I’d expect the output from the console.logs to be:

JavaScript

But instead I’m getting this:

JavaScript

Why is this happening? Since I’m awaiting processRow(), shouldn’t it be in the same scope as the try/catch block, and therefore the catch() should be processed immediately after the processRow() throws an exception?

Advertisement

Answer

If it’s processing multiple lines, parseFile() must have some loop inside. It’s unclear if it’s your code or it’s coming from some library, but that loop either expects to work with asynchronous callbacks, or it doesn’t. Perhaps those unshown options also affect this.

If it used a loop with await, the output would be what you expect:

JavaScript

However if it doesn’t use await, then the loop progresses immediately when wrapper() encounters its own await line:

JavaScript

And if it’s an ancient forEach(), then it doesn’t matter even if it tries to await:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement