Code has been added to clipboard!

Discover JavaScript try catch: Handling JavaScript Error Easily

Reading time 3 min
Published Aug 8, 2017
Updated Oct 2, 2019

There are various practices for handling errors depending on their origin. One of the options is JavaScript try catch. In this tutorial, you will learn about JavaScript try catch, what it is, and how it works.

In addition to JavaScript try catch, you will learn about JavaScript throw statement, which is used together with try catch to provide more user-friendly error handling, and the finally statement, which is used to provide additional functionality when handling JavaScript errors.

JavaScript try catch: Main Tips

  • Errors often occur when executing JavaScript code. There can be different kind of errors: programmer errors, wrong input, etc.
  • The try and catch block lets you set an error handling code: try defines a code of block that will be tested for errors, and catch defines a code of block that handles the error.
  • The throw keyword lets you create a new custom error text.
  • The finally statement defines a block of code that will be executed after try and catch no matter if there was an error or not.

Collaboration Between try and catch

Whenever we wish to test our code for errors, we first have to choose a specific piece to try. This will help us locate an error and save time that we would waste solving it.

The try statement defines this piece of code that will be tested for any possible errors. Now, once an error occurs within the try statement's block of code, the system will execute the code defined by the catch statement.

As you might have understood, these two statements work together, so they always come in pairs. See the example below to get a better understanding of how they work:

Example
try {
    alert("Hey!");
}
catch(err) {
    document.getElementById("error").innerHTML = err.message;
}

Using throw Statement

The throw statement lets you create a new custom error text. It is often used together with try and catch statements in order to control the flow of the program.

You can set a custom throw statement to appear for each condition defined whenever an error occurs in try block of code. As you can see in the code snippet below, it can throw a text, number or boolean:

Example
throw "Value invalid."// throws a string
throw 406// throws a number

Input Validation Example

In the example below, whenever any of the conditions defined in the try block of code are not met, the error occurs. Then, it is caught by the catch statement, and the error message is thrown.

When the user inputs a wrong value, an error message is displayed:

Example
function errorFunction() {
    var errorMsg, x;
    errorMsg = document.getElementById("out");
    errorMsg.innerHTML = "";
    x = document.getElementById("test").value;
    try { 
        if(x == "") throw "empty";
        if(isNaN(x)) throw "not a number";
        x = Number(x);
        if(x < 1) throw "number is too low";
        if(x > 100) throw "number is too high";
    }
    catch(err) {
        errorMsg.innerHTML = "Input is " + err;
    }
}

finally Statement

The finally statement executes its block of code regardless of the results of the try and catch blocks actions.

In the example below, the finally statement defines a block of code which clears out the input upon clicking the Submit button. This action occurs whether there was an error or not:

Example
function errorFunction() {
    var errorMsg, x;
    errorMsg = document.getElementById("out");
    errorMsg.innerHTML = "";
    x = document.getElementById("test").value;
    try { 
        if(x == "") throw "empty";
        if(isNaN(x)) throw "not a number";
        x = Number(x);
        if(x < 1) throw "number is too low";
        if(x > 100) throw "number is too high";
    }
    catch(err) {
        errorMsg.innerHTML = "Input is " + err;
    }
    finally {
      document.getElementById("test").value = "";
    }
}

JavaScript try catch: Summary

  • JavaScript try catch method allows you to catch errors in a program.
  • JavaScript throw allows you to set a specific error message to be thrown.
  • finally statement executes code despite any errors.
What Is JavaScript Used For?
Tutorial
Introduction
Output
Syntax
Comment
Commands
Operators
Comparison and Logical Operators
Data Types
Math.random()
Type Conversion
Function Definitions
Events
Objects
Object Properties
Prototype
Array
Sorting Arrays
Strings
Numbers
Number Format
Math Object
Onclick Event
Date
Date Formats
Scope
Regular Expressions
Reserved Words
Common Mistakes
Performance
Forms
Form Validation
Window: The Browser Object Model
Popup Boxes
Cookies
JSON
AJAX Introduction
AJAX Form
Automatic File Download
Functions
Array Methods
String Methods
Date Methods
Timing Events
Cheat Sheet
JavaScript in HTML
HTML DOM Methods
HTML DOM Changing HTML
HTML DOM Animation
HTML DOM EventListener
HTML DOM Navigation
HTML DOM NodeList
HTML DOM Element Nodes
Array Functions
Boolean
Calling a Function
Date Functions
Global Objects
Input Text
Operator
Statements
String Functions
Math
Math.random
Number
RegEx
alert
array.filter
array.length
array.map
array.reduce
array.push
array.sort
break and continue
className
confirm
decodeURIComponent
for
forEach
if
indexOf
innerHTML
location.reload
number.toString
onclick
onload
parseInt
prompt
replace
setAttribute
setInterval
setTimeout
slice
splice
string.includes
string.indexOf
string.split
style.display
submit
substr
substring
switch
test
throw, try and catch
toLowerCase
toUpperCase
use strict
while
window.history
window.location
window.navigator
window.screen