There are very few situations in JavaScript where exceptions are thrown. First, simply because there are very few places for their occurrence.
Secondly, because the language itself is "forgiving": it overlooks many things, for example, division by zero or incorrect HTML code. Even if you specify the wrong path to the image you are about to load, JavaScript will forgive you and will not consider this an exception.
However, there are exceptional situations. We will analyze the two most simple ones and, using their example, we will study the work with exceptions in JavaScript.
The first exception occurs when we want to parse invalid JSON:
let data = JSON.parse('{1,2,3,4,5}'); // this JSON is invalid
And the second exception occurs when the
local storage allocated for our site is
overflowing (more than 5
megabytes).
Let's artificially raise such an exception:
let str = '';
for (let i = 1; i <= 6 * 10 ** 6; i++) { // we form a string more than 5 MB
str += '+';
}
localStorage.setItem('key', str); // then try to save it in storage
How does JavaScript react to such exceptional situations? It simply dumps an error to the console and stops further script execution.
Our task as programmers is to catch
this situation and somehow deal with
it, not letting the program completely
stop running. For this, there is
a special try-catch
construction,
which we will analyze in the next lessons.
Create a string large enough and try to save it to local storage. Make sure there is an error in the console.
Try to parse invalid JSON. Make sure there is an error in the console.