Try Catch Throw
Easy Programming tutorial on how to throw custom errors in JavaScript
by Nazmus Nasir
HTML
<!-- JavaScript Objects - try...catch...throw #45 -->
<p>
Welcome to the 45th Easy JavaScript tutorial, part of <a href="http://www.easyprogramming.net">EasyProgramming.net</a>. Let's look a little more into <code>try...catch</code> by looking at the <code>throw</code> function you can use to include your own custom error messages.
</p>
<p>
Custom errors can be defined by you based on logic that you've entered. You don't have to rely on the 5 basic errors that JavaScript tends to throw, make up your own!
</p>
<h2>
Syntax of <code>try...catch()</code>:</h2>
<p>
<code><pre>
<span class="keyword">try</span>{
//run code and validate something
<span class="keyword">throw</span>("Custom error message if validation failed");
} <span class="keyword">catch</span> (error) {
//Do something the code can't run or returns an error
//the <code>error</code> parameter chere is what the throw() function sent back
//error.name or error.message do not work here, just look for error
<span class="keyword">console</span>.log(error); //outputs: "Custom error message if validation failed" into the JS Console
}
</pre>
</code>
</p>
<p>
<h2>
Let's practice:</h2>
<p>
Enter a number between 1 and 10
</p>
<span id="output"></span>
<br /><br />
<input type="text" id="num" />
<!-- <input type="text" id="num2" /> -->
<button id="button">
Submit
</button>
<br /><br /><br /><br /><br /><br />
CSS
.keyword {
color: #a151d2;
}
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
td {
padding: 5px 10px;
}
JavaScript
var button = document.getElementById("button");
button.addEventListener("click",function(e){
try {
var num = document.getElementById("num").value;
if(num < 0){
throw("Number is too low, try again");
}
if(num > 10){
throw("Number is too high, try try again!");
}
if(!parseInt(num)){
throw("Enter a number please!!!");
}
document.getElementById("output").innerText = num;
} catch (e) {
document.getElementById("output").innerText = e;
}
});