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);
}
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>
<p id="error"></p>
<script>
try {
wrongalert("Welcome guest!");
}
catch(err) {
document.getElementById("error").innerHTML = err.message;
}
</script>
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
}
let json = '{ "age": 30 }'; // incomplete data
try {
let user = JSON.parse(json); // <-- no errors
alert( user.name ); // no name!
} catch (e) {
alert( "doesn't execute" );
}