Try Catch Finally
Learn better error handling from this EasyProgramming.net tutorial
by Nazmus Nasir
HTML
<!-- JavaScript Objects - try...catch...finally #44 -->
<p>
Welcome to the 44th Easy JavaScript tutorial, part of <a href="http://www.easyprogramming.net">EasyProgramming.net</a>. We've looked at how to debug JavaScript in the past, let's go a little further by looking at <code>try...catch</code>. In the next tutorial, we'll cover throw().
</p>
<p>
The try...catch block can throw 5 types of errors and two properties. The properties are always 'name' and 'message' - the errors are:
</p>
<table>
<thead><th>Name</th><th>Description</th></thead>
<tbody>
<tr><td>RangeError</td> <td>A number "out of range" has occurred</td></tr>
<tr><td>ReferenceError</td> <td>An illegal reference has occurred</td></tr>
<tr><td>SyntaxError</td> <td>A syntax error has occurred</td></tr>
<tr><td>TypeError</td> <td>A type error has occurred</td></tr>
<tr><td>URIError</td> <td>An error in encodeURI() has occurred</td></tr>
</tbody>
</table>
<h2>
Syntax of <code>try...catch()</code>:</h2>
<p>
<code><pre>
<span class="keyword">try</span>{
//run code
} <span class="keyword">catch</span> (error) {
//Do something the code can't run or returns an error
//the <code>error</code> parameter can be used to get the name and message
//e.g. error.name or error.message
} <span class="keyword">finally</span> {
//this code runs no matter what
}
</pre>
</code>
</p>
<p>
<h2>
Let's practice:</h2>
<span id="output"></span>
<br /><br />
<br /><br /><br /><br />
<!-- <input type="text" id="num1" /> -->
<!-- <input type="text" id="num2" /> -->
<!-- <button id="button">
Submit
</button>
-->
CSS
.keyword {
color: #a151d2;
}
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
td {
padding: 5px 10px;
}
JavaScript
var a = 5;
var b = 10;
try{
document.getElementById('output').innerText = a * b;
} catch (e) {
document.getElementById('output').innerText = 'There was a ' + e.name + '. The message is ' + e.message + '.';
} finally {
document.getElementById('output').innerHTML += "<br />This line always runs";
}
try {
a("hello");
} catch (e){
document.getElementById('output').innerHTML += '<br />There was a ' + e.name + '. The message is ' + e.message + '.';
}