try {
// code may cause error
} catch(error){
// code to handle error
}
try {
alert('Start of try runs'); // (1) <--
lalala; // error, variable is not defined!
alert('End of try (never reached)'); // (2)
} catch(err) {
alert(`Error has occurred!`); // (3) <--
}
(function() {
try {
try {
throw new Error('oops');
} catch (ex) {
console.error('inner', ex.message);
throw ex;
} finally {
console.log('finally');
return;
}
} catch (ex) {
console.error('outer', ex.message);
}
})();
// Output:
// "inner" "oops"
// "finally"
const numerator= 100, denominator = 'a';
try {
console.log(numerator/denominator);
console.log(a);
}
catch(error) {
console.log('An error caught');
console.log('Error message: ' + error);
}
finally {
console.log('Finally will execute every time');
}
try {
// try_statements
}
catch(error) {
// catch_statements
}
finally() {
// codes that gets executed anyway
}