Learning JavaScript
Exceptions
Syntax for catch statement
try {
...
}
catch {
...
}
//example:
const calcPayments = (numPayments, rate, totalPrice) => {
try {
let monthPay = ((totalPrice * rate) + totalPrice) / numPayments
}
catch (error) {
alert(error.message)
}
};
Catch block with custom message
catch(error) {
alert("Loan rate not calculated. Check the calcPayments function")
};
//catch block with no error (available as of ES2019)
catch {
alert("calcPayments has thrown error")
};
Create error object / Throw statement
new Error(message)
throw errorObj;
//example
const calcPayments = (numPayments, rate, totalPrice) => {
if(isNaN(numPayments) || isNaN(rate) || isNaN(totalPrice)) {
throw new Error ("calcPayments incorrect, check loan numbers")
}
return ((totalPrice * rate) + totalPrice) / numPayments
};
Finally statement
//finally will execute regardless if try or catch is thrown
try {
$("some_value").text = sendToFunction(parameters);
}
catch(error) {
alert("parameters not accepted");
}
finally {
$("parameters").focus()
}