Rethrowing an exception in JavaScript
Let's consider the catch-block of
the task with product JSON:
catch (error) {
if (error.name == 'SyntaxError') {
alert('Invalid JSON of the product');
} else if (error.name == 'ProductCostError') {
alert('Product has no price or amount');
}
}
As you can see, we catch the two exceptions
we planned and somehow react to it. But what
happens if an exception of a different type
that we didn't expect occurs? In this case,
it will also fall into a catch-block,
but there will be no reaction to this, since
the exception with a different type simply
will not fall into any of our IFs.
When I say that there will be no reaction, I mean that there really is none: there will not even be an error thrown into the console. Our code just silently won't work.
Therefore, there is the following rule: your
code should only catch exceptions that it
knows how to handle. If the exception is not
known, then it must be rethrow further
with throw. In this case, someone more
knowledgeable will catch it above, or an
exception will be thrown into the console
as an error.
Let's fix our code:
catch (error) {
if (error.name == 'SyntaxError') {
alert('Invalid JSON of the product');
} else if (error.name == 'ProductCostError') {
alert('Product has no price or amount');
} else {
throw error; // rethrow the exception further
}
}
Given the following code:
try {
let arr = JSON.parse(json);
for (let i = 0; i < arr.length; i++) {
localStorage.setItem(i, arr[i]);
}
} catch (error) {
if (error.name == 'QuotaExceededError') {
alert('ran out of storage space');
}
if (error.name == 'SyntaxError') {
alert('invalid json');
}
}
What's wrong with this code? Fix it for a better one.