Answer the question
In order to leave comments, you need to log in
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
If an error occurs within the block try
, the variable e
will 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 questionAsk a Question
731 491 924 answers to any question