Mastering Error Handling in JavaScript: Best Practices and Techniques for Robust Code

Gopal Khadka
3 min readOct 17, 2023

--

Since JavaScript is a loosely typed language (programming language where variables are not bound to a specific data type during declaration), the code is bound to throw errors when you try to access undeclared or undefined variables or call undefined functions.

Similar to the other languages like Java and Python, JavaScript provides us a way to handle those errors. The try-catch-finally statement is used to deal with those possible errors. Its syntax is given below:

try {
// code that may throw an error
} catch (err) {
// code to be executed if an error occurs
} finally {
// code to be executed regardless of an error occurs or not
}
  1. try: It wraps up the code that might throw possible errors
  2. catch: It catches the errors and wraps up the code to execute when the error is caught. It is usually used to show error messages to the user.
  3. finally: It contains code that is executed regardless of occurrence of the errors. It is usually used to reset the variables that might have been changed inside try statement.

Let’s look at a few examples:

try {
let lastName = 'Khadka'
let fullName = firstName + ' ' + lastName
} catch (err) {
console.log(err) // ReferenceError: firstName is not defined
}

Since the variable named “firstName” is not defined, and we try to access it, it throws the ReferenceError which is caught inside the catch block. The error is directly printed to the console inside the catch block.

try {
let lastName = 'Khadka'
let fullName = firstName + ' ' + lastName
} catch (err) {
console.error(err) // ReferenceError: firstName is not defined
} finally {
console.log('In any case I will be executed') // In any case it will be executed
}

From the above code, we can see that even if the error occurs, the finally block gets executed at last. To clarify the error more precisely, we can access its attributes like this:

try {
let lastName = 'Khadka'
let fullName = firstName + ' ' + lastName
} catch (err) {
console.log('Name of the error: ', err.name) // Name of the error: ReferenceError
console.log('Error message: ', err.message) // Error message: firstName is not defined
} finally {
console.log('In any case I will be executed') // In any case I will be executed
}

The error mentioned above (ReferenceError) is predefined in the language. You can learn about more error of JavaScript here. Let’s discuss common errors in brief here:

1. Syntax Error

It is thrown when there is error in the syntax

let square = 2 x 2 //  Uncaught SyntaxError: Unexpected identifier
console.log(square)

2. Reference Error

It is thrown when we try to access the undeclared variables or functions.

let firstName = 'Gopal'
let fullName = firstName + ' ' + lastName // Uncaught ReferenceError: lastName is not defined
console.log(fullName)

3. Type Error

A type error occurs when you try to call a method or attribute of one object on another type of the object.

let num = 10
console.log(num.toLowerCase()) // Uncaught TypeError: num.toLowerCase is not a function

These errors are fine in most cases to catch errors. What if your error is not predefined? Worry not. You can create your own custom errors and throw exceptions. You can throw error as string, number, boolean or error object.

throw 'Error2' // generates an exception with a string value
throw 42 // generates an exception with the value 42
throw true // generates an exception with the value true
throw new Error('Required') // generates an error object with the message of Required

Let’s learn more of this with an example:

const throwErrorExampleFun = () => {
let message
let x = prompt('Enter a number: ') // taking input from user
try {
if (x == '') throw 'empty' // handling empty input
if (isNaN(x)) throw 'not a number' // handling non numeric values
x = Number(x) // converting value into Number object
if (x < 5) throw 'too low' // handling the number less than 5
if (x > 10) throw 'too high' // // handling the number more than 10
} catch (err) {
console.log(err) // handling all other possible errors
}
}
throwErrorExampleFun()

This concludes the basic application and understanding of the error handling in JavaScript. Hope it helps !

--

--

Gopal Khadka

Aspiring coder and writer, passionate about crafting compelling stories through code and words. Merging creativity and technology to connect with others.