Reputation: 319
Please elaborate on the what exactly this means:
'As a general rule, don’t blanket-catch exceptions unless it is for the purpose of “routing” them somewhere—for example, over the network to tell another system that our program crashed. And even then, think carefully about how you might be hiding information.' - Eloquent Javascript
Upvotes: 1
Views: 85
Reputation: 135752
Assuming you mean the explanation here:
for (;;) { try { var dir = promtDirection("Where?"); // ← typo! console.log("You chose ", dir); break; } catch (e) { console.log("Not a valid direction. Try again."); } }
The
for (;;)
construct is a way to intentionally create a loop that doesn’t terminate on its own. We break out of the loop only when a valid direction is given. But we misspelledpromptDirection
, which will result in an“undefined variable”
error. Because thecatch
block completely ignores its exception value (e
), assuming it knows what the problem is, it wrongly treats the variable error as indicating bad input. Not only does this cause an infinite loop, but it also “buries” the useful error message about the misspelled variable.As a general rule, don’t blanket-catch exceptions unless it is for the purpose of “routing” them somewhere—for example, over the network to tell another system that our program crashed. And even then, think carefully about how you might be hiding information.
So we want to catch a specific kind of exception. We can do this by checking in the catch block whether the exception we got is the one we are interested in and by rethrowing it otherwise. (...)
I believe what the author means by "blanket-catch" exceptions is to catch an exception and don't verify its content at all, believing you are 100% sure it will always be a certain kind of error.
The example code shows a "blanket-catch" that assumed it would only happen when the user provided an invalid direction, but the error is actually caused by a typo in the code.
Since the catch
didn't really verify if the error was really an invalid direction (there's no if
in the catch
, nor it prints e
's content), it caught (swallowed into the oblivion) a different error* believing it was an invalid direction one - ultimately handling the exception for the wrong reason.
* The error would be undefined is not a function
instead of undefined variable
as the author points out.
Upvotes: 1