Catching exceptions in JavaScript

The try-catch construct is used to catch exceptions. It has the following syntax:

try { // a code } catch (error) { // an error handling }

The try-block should contain code that may contain an exception. If suddenly an exception occurs when executing this code, then our script will not crash with an error in the console, but the code of the catch-block will be executed.

In this block, we must somehow adequately react to the error. For example, if we wanted to send some data via the Internet and the Internet does not work, in a catch-block we can somehow handle the situation: we can, for example, display a message to an user, or we can try to send this data again - suddenly the Internet is already working.

If, however, no exceptions occurred during the execution of a try-block, then the useful code will simply be executed, while the code from a catch block will not.

For example, let's try to parse JSON and, if it is invalid, we will display a message about it on the screen:

try { let data = JSON.parse('{1,2,3,4,5}'); } catch (error) { alert('unable to parse JSON'); }

Given a code that save some string to a local storage:

let str = 'some string'; localStorage.setItem('key', str);

Wrap this code in a try-catch construct. In the catch-block, display a message about storage overflow. Test your code for a string smaller than 5 MB and for a larger string.

Given a JSON containing an array. If this JSON is correct, then output the elements of the array as a ul list. If the JSON is not valid, display a message on the screen saying that an error has occurred on the page.

enru