# 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:

`function 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:

`try { save('some string'); } catch (error) { alert('ran out of local storage space!'); }`

Given a function that converts JSON to an array:

`function getArr(json) { return JSON.parse(json); }`

In the following code, an array is retrieved from JSON:

`let arr = getArr('[1,2,3,4,5]'); console.log(arr);`

Wrap the function call in `try-catch`.

← →
↑
en ru