Try/Catch/Finally - Exercise

Welcome to our free Advanced JavaScript Programming tutorial. This tutorial is based on Webucator's Advanced JavaScript Programming course.

Contact Us or call 1-877-932-8228
Try/Catch/Finally - Exercise


Duration: 10 to 15 minutes.

In this exercise, you will handle potentially-problematic user input in a simple calculator, designed to return the quotient of two user-entered numbers.

  1. Open ErrorsException/Exercises/trycatch.html for editing.
  2. The result of the user clicking the "=" button is to write to the #msg div one of the following:
    • "both operands must be a number" if either the dividend or divisor (or both) is not a number or is blank;
    • "cannot divide by zero" if the divisor == 0; or
    • the answer, if both dividend and divisor are valid numbers.
    and to clear the fields of entered values.
  3. Use try/catch/finally for error handling.
  4. Test your solution in a browser.


<meta charset="UTF-8">
    input.operator {
    input#quotient {
<script type="text/javascript">
    function DisplayAnswer() {
        var dividendField = document.getElementById('dividend');
        var divisorField = document.getElementById('divisor');
        var msgField = document.getElementById('msg');

        var dividend = dividendField.value;
        var divisor = divisorField.value;
        var quotient;

        try {
            if (isNaN(dividend) || isNaN(divisor) || dividend=='' || divisor=='') {
                throw new Error("both operands must be a number");
            } else if (+divisor == 0) {
                throw new Error("cannot divide by zero");
            } else {
                quotient = dividend / divisor;
                msg.innerHTML = dividend  + " / " + divisor + " = " + quotient;
        catch (e) {
            msg.innerHTML = 'There was a problem: ' + e.message;
        finally {
            dividendField.value = '';
            divisorField.value = '';

    window.onload = function() {
        var equals = document.getElementById('equals');
        equals.addEventListener('click', DisplayAnswer, false)

<input type="text" id="dividend" class="operator"> / <input type="text" id="divisor" class="operator"> <button id="equals">=</button>
<div id="msg"></div>

Code Explanation

In the try block we check for not-a-number-ness for the two user-entered values. If valid, we then check to make sure that the divisor is not zero. If either test fails, we throw a custom error. If neither test fails, then we write the answer to the #msg div.

If an error occurred, then our catch block writes the error to the #msg div.

We use the finally block to clear the user-input fields.


This tutorial is based on Webucator's Advanced JavaScript Programming Course. We also offer many other JavaScript Training courses. Sign up today to get help from a live instructor.