try {
// Try to run this code
}
catch(err) {
// if any error, Code throws the error
}
finally {
// Always run this code regardless of error or not
//this block is optional
}
var someNumber = 1;
try {
someNumber.replace("-",""); //You can't replace a int
} catch(err) {
console.log(err);
}
//Catch is the method used when your promise has been rejected.
//It is executed immediately after a promise's reject method is called.
//Here’s the syntax:
myPromise.catch(error => {
// do something with the error.
});
//error is the argument passed in to the reject method.
async function getData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
const data = await response.json();
const { userId, id, title, completed } = data;
console.log(userId, id, title, completed);
} catch(err) {
alert(err)
}
}
getData();
try {
// code may cause error
} catch(error){
// code to handle error
}
<html>
<head>Exception Handling</head>
<body>
<script>
try {
throw new Error('This is the throw keyword'); //user-defined throw statement.
}
catch (e) {
document.write(e.message); // This will generate an error message
}
</script>
</body>
</html>
try {
const test = 'string1'
console.log(test)
test = 'string2'
console.log(test)
} catch (e) {
console.log(e.stack)
}
try {
// Try to run this code
}
catch(err) {
// if any error, Code throws the error
}
finally {
}
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) <--
}
try {
// body of try
}
catch(error) {
// body of catch
}
// returns a promise
let countValue = new Promise(function (resolve, reject) {
reject('Promise rejected');
});
// executes when promise is resolved successfully
countValue.then(
function successValue(result) {
console.log(result);
},
)
// executes if there is an error
.catch(
function errorValue(result) {
console.log(result);
}
);