O
O
olya_0972018-02-25 02:49:30
JavaScript
olya_097, 2018-02-25 02:49:30

Why is e needed here in catch?

var data = '{ "age": 30 }'; // данные неполны

try {

  var user = JSON.parse(data); // <-- выполнится без ошибок

  if (!user.name) {
    throw new SyntaxError("Данные некорректны");
  }

  alert( user.name );

} catch (e) {
  alert( "Извините, в данных ошибка" );
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
y0u, 2018-02-25
@olya_097

If an error occurs within the block try, the variable ewill contain an object with information about the error.

var data = '{ "age": 30 }';

try {

    var user = JSON.parse(data);

    if (!user.name) {
        throw new SyntaxError("Данные некорректны");
    }

    alert(user.name);

} catch (e) {
    console.log(e); // SyntaxError: Данные некорректны
    console.log(e.name); // SyntaxError
    console.log(e.message); // Данные некорректны
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question