Animations

API

Arrays

Async

Basics

Challenges

Classes

Console

Dates

Debugging

DOM Elements

DOM Methods

DOM Navigation

DOM Properties

Event Listeners

Flow Control

Forms

Functions

Global Functions

JSON

Keywords

Libraries (3rd party)

Math

Modules

Objects

Snippets

String

Types

Widgets

Window Object

JavaScript - Try Catch

The try statement lets you test a block of code for errors. The catch statement lets you handle the error. The throw statement lets you create custom errors. The finally statement lets you execute code, after try and catch, regardless of the result.

  • Open Developer Console
  • Click button...see error

Try Catch Finally Example


function RunTest1()
{
    let output = "";
    let demo1 = document.getElementById("demo1");

    try
    {
        for (let i = 0; i < 5; i++)
        {
            output +=`The number is ${i}<br />`;
        }
allert("all done");
    }
    catch (error)
    {
        output = error.message;
    }
    finally
    {
        demo1.innerHTML = output;
    }
}

 


Try Catch Finally with Throw Example

It may be beneficial to use the try..catch with execution flow errors. To do it, we should be able to raise our own errors, which is done by throw.

The syntax is: throw {name}, where {name} is literally anything. No matter what you throw, it will be caught by the catch...Or make the program die if throw is done out of try section.



function RunTest2()
{
    let demo2 = document.getElementById("demo2");

    try
    {
        //try any of these
        let age = 200;
        //let age = 50;
        //let age = "bob";
        ValidateAge(age);
        demo2.innerHTML = "Age is valid";
    }

    catch (error)
    {
        demo2.innerHTML = "Error: " + error.message;
    };
}

function ValidateAge(age)
{
    if (isNaN(age))
    {
        throw { name: 'NotANumberError', message: 'Invalid age - Not a number!' };
    }

    if (age < 5 || age> 150)
    {
        throw { name: 'OutOfRangeError', message: 'Age out of range' };
    }

}