xxxxxxxxxx
try {
// body of try
}
catch(error) {
// body of catch
}
xxxxxxxxxx
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
}
xxxxxxxxxx
var someNumber = 1;
try {
someNumber.replace("-",""); //You can't replace a int
} catch(err) {
console.log(err);
}
xxxxxxxxxx
//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.
xxxxxxxxxx
try {
const test = 'string1'
console.log(test)
test = 'string2'
console.log(test)
} catch (e) {
console.log(e.stack)
}
xxxxxxxxxx
<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>
xxxxxxxxxx
try {
// code may cause error
} catch(error){
// code to handle error
}
xxxxxxxxxx
try {
// code
throw new Error('Whoops!');
}
catch(err) {
// handle exception
console.log("Intentional thrown Error is caught");
}
finally {
// optional code to be run at the end
console.log("Whether or not there is error, I will show up");
}
xxxxxxxxxx
function getuser(number){
if(isNaN(number)){
throw new Error(number + " is not a numbre")
}
};
try{
const a = getuser('hello');
}
catch(error){
console.log(error)
}
xxxxxxxxxx
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) <--
}