Catching exceptions in a nested code in JavaScript
The peculiarity and convenience of exceptions is that they can be caught at any level of code nesting. Let's look at an example. Suppose we have a function that saves data to a local storage:
javascriptfunction save(str) {
localStorage.setItem('key', str);
}
As you already know, when a storage
overflows, the setItem method
will throw an exception. It is not
necessary, however, to catch this
exception inside the save
function. You can wrap in try
each call to the function itself:
javascripttry {
save('some string');
} catch (error) {
alert('ran out of local storage space!');
}
Задание 1
Given a function that converts JSON to an array:
javascriptfunction getArr(json) {
return JSON.parse(json);
}
In the following code, an array is retrieved from JSON:
javascriptlet arr = getArr('[1,2,3,4,5]');
console.log(arr);
Wrap the function call
in try-catch.