xxxxxxxxxx
<body>
<div id="error"> </div>
<script>
try{
if(x==1)
{
throw "x must not be 1";
}
}
catch(err)
{
document.getElementById("error").innerHTML = err;
}
</script>
</body>
xxxxxxxxxx
try {
throw new Error('Whoops!')
} catch (e) {
console.error(e.name + ': ' + e.message)
}
xxxxxxxxxx
const number = 40;
try {
if(number > 50) {
console.log('Success');
}
else {
// user-defined throw statement
throw new Error('The number is low');
}
// if throw executes, the below code does not execute
console.log('hello');
}
catch(error) {
console.log('An error caught');
console.log('Error message: ' + error);
}
xxxxxxxxxx
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" );
}
xxxxxxxxxx
<body>
<h2>JavaScript try catch</h2>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="p01"></p>
<script>
function myFunction() {
const message = document.getElementById("p01");
message.innerHTML = "";
let x = document.getElementById("demo").value;
try {
if(x.trim() == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch(err) {
message.innerHTML = "Input is " + err;
}
}
</script>
</body>